When to use a filter vs a directive in Angularjs

All we need is an easy explanation of the problem, so here it is.

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 vice versa?

In a really really simple example, see this Plunkr

Essentially, I have the following javascript

var app = angular.module('app', []);

app.controller('MyCtrl', ['$scope', function($scope){
  $scope.testMessage = 'Some Text'
}]);

app.directive('myDirective', function(){
    return{ 
        restrict: 'A',
        link: function(scope, element, attrs){

            // do some stuff with the data
            // 
            element.html(scope.testMessage + ' result of my directive');
        }
    }
});

app.filter('myFilter', function(){
    return function(text){
     // do something with text
        return text + ' & result of my filter';
    }
});

And the following html

  <body ng-controller="MyCtrl">
    <div my-directive ng-model="testMessage" ></div>
    <br />
    <div>{{ testMessage | myFilter }}</div>
  </body>

So when would you use one over the other?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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)

Method 2

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>

Method 3

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.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply