user2368436 user2368436 - 1 year ago 68
AngularJS Question

AngularJS custom filter function

Inside my controller, I would like to filter an array of objects. Each of these objects is a map which can contain strings as well as lists

I tried using

$filter('filter')(array, function)
format but I do not know how to access the individual elements of the array inside my function. Here is a snippet to show what I want.

$filter('filter')(array, function() {
return criteriaMatch(item, criteria);

And then in the
, I will check if each of the individual property matches

var criteriaMatch = function(item, criteria) {
// go thro each individual property in the item and criteria
// and check if they are equal

I have to do all these in the controller and compile a list of lists and set them in the scope. So I do need to access the
this way only. All the examples I found in the net so far have static criteria searches inside the function, they don't pass an criteria object and test against each item in the array.

Answer Source

You can use it like this:

Like you found, filter accepts predicate function which accepts item by item from the array. So, you just have to create an predicate function based on the given criteria.

In this example, criteriaMatch is a function which returns a predicate function which matches the given criteria.


<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
  {{ item }}


$scope.criteriaMatch = function( criteria ) {
  return function( item ) {
    return ===;