AngularJS : Custom filters and ng-repeat AngularJS : Custom filters and ng-repeat angularjs angularjs

AngularJS : Custom filters and ng-repeat


If you want to run some custom filter logic you can create a function which takes the array element as an argument and returns true or false based on whether it should be in the search results. Then pass it to the filter instruction just like you do with the search object, for example:

JS:

$scope.filterFn = function(car){    // Do some tests    if(car.carDetails.doors > 2)    {        return true; // this will be listed in the results    }    return false; // otherwise it won't be within the results};

HTML:

...<article data-ng-repeat="result in results | filter:search | filter:filterFn" class="result">...

As you can see you can chain many filters together, so adding your custom filter function doesn't force you to remove the previous filter using the search object (they will work together seamlessly).


If you still want a custom filter you can pass in the search model to the filter:

<article data-ng-repeat="result in results | cartypefilter:search" class="result">

Where definition for the cartypefilter can look like this:

app.filter('cartypefilter', function() {  return function(items, search) {    if (!search) {      return items;    }    var carType = search.carType;    if (!carType || '' === carType) {      return items;    }    return items.filter(function(element, index, array) {      return element.carType.name === search.carType;    });  };});

http://plnkr.co/edit/kBcUIayO8tQsTTjTA2vO?p=preview


You can call more of 1 function filters in the same ng-repeat filter

<article data-ng-repeat="result in results | filter:search() | filter:filterFn()" class="result">