Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to angularjs filters

Is it possible to pass an argument to the filter function so you can filter by any name?

Something like

$scope.weDontLike = function(item, name) {     console.log(arguments);     return item.name != name; }; 
like image 656
shapeshifter Avatar asked Aug 01 '12 05:08

shapeshifter


1 Answers

Actually there is another (maybe better solution) where you can use the angular's native 'filter' filter and still pass arguments to your custom filter.

Consider the following code:

<div ng-repeat="group in groups">     <li ng-repeat="friend in friends | filter:weDontLike(group.enemy.name)">         <span>{{friend.name}}</span>     <li> </div> 

To make this work you just define your filter as the following:

$scope.weDontLike = function(name) {     return function(friend) {         return friend.name != name;     } } 

As you can see here, weDontLike actually returns another function which has your parameter in its scope as well as the original item coming from the filter.

It took me 2 days to realise you can do this, haven't seen this solution anywhere yet.

Checkout Reverse polarity of an angular.js filter to see how you can use this for other useful operations with filter.

like image 55
Denis Pshenov Avatar answered Sep 29 '22 09:09

Denis Pshenov