Using Filters With Directives in AngularJS
Solution 1
You're creating a new isolate scope on the directive (scope: { 'fancyDisplay': '=' }
), that means you won't be able to access properties from the parent scope. Since tagFilter
is defined on the parent scope, you won't be able to access it.
Pass tagFilter
as an attribute to the directive:
<div fancy-display="model.data" filter="tagFilter"></div>
And on the directive:
scope: {
fancyDisplay: '=',
tagFilter: '=filter'
},
jsfiddle: http://jsfiddle.net/bmleite/VDLqa/5/
Solution 2
Thanks to @bmleite for your answer.
Another thing that might be helpful is to make sure to declare your ng-repeat directive like this incase you have deplicates on your list.
It took me forever to figure this out. Apparently you must filter before you specify the track by x :
app.directive("someDirective", function(){ ...
restrict: "E",
...
template:"<ul ng-repeat='t in tree | filter:key track by $index'><li>{{t}}</li></ul>",
});
The inverse does not work.
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Admin
Updated on July 09, 2022Comments
-
Admin almost 2 years
I'm attempting to use filters within an AngularJS directive but not sure exactly how to do so. From some info on the mailing list it appears that you should be able to inject $filter and use it, but I'm not sure how/where to invoke it.
My directive currently looks like this:
myApp.directive('fancyDisplay', ['$filter', function($filter) { return { scope: { 'fancyDisplay': '=' }, template: "<div ng-repeat='datum in fancyDisplay | filter:tagFilter'>{{datum.name}}</div>" }; }]);
Although the
filter:tagFilter
isn't working. How should I filter my data in the directive?JSfiddle available at http://jsfiddle.net/VDLqa/4/ Thanks in advance for any responses.
-
Admin over 11 yearsHmm... how would I extend that to multiple filters?
-
bmleite over 11 yearsDefine more attrs:
<div fancy-display="model.data" filter1="filter1" filter2="filter2"></div>
and on the directivescope: { fancyDisplay: '=', filter1: '=', filter2: '=' }
. Note: I've called them 'filter1' and 'filter2' but you can call them whatever you want. Also, if you start having many filters, I would recommend you to pre-filter theng-model
data before sending it to the directive. -
Admin over 11 yearsPre-filtering is interesting as that's where I started. I tried this on the directive itself but it didn't work; how would I alter the fiddle to achieve this?
-
bmleite over 11 yearsOn the watchers, add something like:
$scope.model.filteredData = $filter('filter')($scope.model.data, $scope.tagFilter);
and on the HTML:<div fancy-display="model.filteredData"></div>
jsfiddle.net/bmleite/VDLqa/6 (note: don't forget to inject the$filter
on the controller). -
Pablo over 8 yearsThanks man! I wast just forgetting to add the
['$filter', function($filter)