When to use a filter vs a directive in Angularjs

前端 未结 3 1034
野的像风
野的像风 2021-02-05 10:37

It\'s a simple question - and it may have been asked (just couldn\'t find it..)

When would you use a filter over a directive when it comes to manipulating the data, or v

相关标签:
3条回答
  • 2021-02-05 11:00

    One more point I want to add apart from

    1. Filter for general Data filtering / transformation
    2. Directive for DOM Manipulation / UI behavior

    Generally we use filters for an array of data.

    I feel like there is no logical difference between them. Both does the same job. It is usage which is different.

    0 讨论(0)
  • 2021-02-05 11:04

    Some hints (non-exhaustive lists):

    Directive

    Use it when...

    • You want to do structural manipulation of the DOM
    • You want to add behaviour (the controller)
    • The outcome is dependent on other collaborators (the require configuration of the directive)

    Filter

    Use it when...

    • You are transforming a value to another (e.g. String → Date)
    • (Subset of the above, but important to warrant it's own bullet:) When you are transforming an array (e.g. to be displayed in repeated elements - the filter filter and ng-repeat)
    0 讨论(0)
  • 2021-02-05 11:06

    Clear and simple

    Filter for general Data filtering / transformation

    Directive for DOM Manipulation / UI behavior


    In your case you can write it like so:

      <div>{{ testMessage + ' result' }}</div>
    
    0 讨论(0)
提交回复
热议问题