Using Filters With Directives in AngularJS

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.

Answers


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/


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.


Need Your Help

If a CSS rule changes, does the browser need to be refreshed

html css css-reset

If I have changed a CSS rule via javascript, do I need to do anything to "refresh" the browser to redisplay the current page using the updated rules?

What's the macro to distinguish ifort from other fortran compilers?

preprocessor fortran intel

I'm working with Fortran code that has to work with various Fortran compilers (and is interacting with both C++ and Java code). Currently, we have it working with gfortran and g95, but I'm research...