[javascript] 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;
};

This question is related to javascript angularjs angular-filters

The answer is


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.


You can simply do like this In Template

<span ng-cloak>{{amount |firstFiler:'firstArgument':'secondArgument' }}</span>

In filter

angular.module("app")
.filter("firstFiler",function(){

    console.log("filter loads");
    return function(items, firstArgument,secondArgument){
        console.log("item is ",items); // it is value upon which you have to filter
        console.log("firstArgument is ",firstArgument);
        console.log("secondArgument ",secondArgument);

        return "hello";
    }
    });

You can pass multiple arguments to angular filter !

Defining my angular app and and an app level variable -

var app = angular.module('filterApp',[]);
app.value('test_obj', {'TEST' : 'test be check se'});

Your Filter will be like :-

app.filter('testFilter', [ 'test_obj', function(test_obj) {
    function test_filter_function(key, dynamic_data) {
      if(dynamic_data){
        var temp = test_obj[key]; 
        for(var property in dynamic_data){
            temp = temp.replace(property, dynamic_data[property]);
        }
        return temp;
      }
      else{
        return test_obj[key] || key;
      }

    }
    test_filter_function.$stateful = true;
    return test_filter_function;
  }]);

And from HTML you will send data like :-

<span ng-bind="'TEST' | testFilter: { 'be': val, 'se': value2 }"></span>

Here I am sending a JSON object to the filter. You can also send any kind of data like string or number.

also you can pass dynamic number of arguments to filter , in that case you have to use arguments to get those arguments.

For a working demo go here - passing multiple arguments to angular filter


From what I understand you can't pass an arguments to a filter function (when using the 'filter' filter). What you would have to do is to write a custom filter, sth like this:

.filter('weDontLike', function(){

return function(items, name){

    var arrayToReturn = [];        
    for (var i=0; i<items.length; i++){
        if (items[i].name != name) {
            arrayToReturn.push(items[i]);
        }
    }

    return arrayToReturn;
};

Here is the working jsFiddle: http://jsfiddle.net/pkozlowski_opensource/myr4a/1/

The other simple alternative, without writing custom filters is to store a name to filter out in a scope and then write:

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

Extending on pkozlowski.opensource's answer and using javascript array's builtin filter method a prettified solution could be this:

.filter('weDontLike', function(){
    return function(items, name){
        return items.filter(function(item) {
            return item.name != name;
        });
    };
});

Here's the jsfiddle link.

More on Array filter here.


Actually you can pass a parameter ( http://docs.angularjs.org/api/ng.filter:filter ) and don't need a custom function just for this. If you rewrite your HTML as below it'll work:

<div ng:app>
 <div ng-controller="HelloCntl">
 <ul>
    <li ng-repeat="friend in friends | filter:{name:'!Adam'}">
        <span>{{friend.name}}</span>
        <span>{{friend.phone}}</span>
    </li>
 </ul>
 </div>
</div>

http://jsfiddle.net/ZfGx4/59/


You can simply use | filter:yourFunction:arg

<div ng-repeat="group in groups | filter:weDontLike:group">...</div>

And in js

$scope.weDontLike = function(group) {
//here your condition/criteria
return !!group 
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to angular-filters

How to filter array when object key value is in array AngularJS : Custom filters and ng-repeat How to filter (key, value) with ng-repeat in AngularJs? How to use a filter in a controller? Passing arguments to angularjs filters