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?
AngularJS Filters allow us to format the data to display on UI without changing original format. Filters can be used with an expression or directives using pipe | sign. Angular includes various filters to format data of different data types.
Filter is an important part in AngularJS as well as Angular 2 or Angular 4. It is basically used to filter an item from a group of items, which are there in an array or an object array. It selects a subset of the items from an array and returns it as a new array and this item is displayed on UI.
Directives are markers on a DOM element that tell AngularJS to attach a specified behavior to that DOM element or even transform the DOM element and its children. In short, it extends the HTML. Most of the directives in AngularJS are starting with ng- where ng stands for Angular.
In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope. finalResult = $filter("filter")( $scope.
Some hints (non-exhaustive lists):
Use it when...
require
configuration of the directive)Use it when...
filter
filter and ng-repeat
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With