Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: filter repeat match against list

I have a list of objects that gets looped over by ngRepeat:

hashes = [
  {
      "type": "foo"
    , …
  }
  , {
      "type": "foo"
    , …
  }
  , {
      "type": "bar"
    , …
  }
]

I want to filter them based on type if it's value matches a item in a list of needles:

types = ['foo','quz'];

so something like

<div ng-repeat="hash in hashes | filter:types"></div>

Is this built into Angular or would I have to write a custom filter?

like image 255
Jakob Jingleheimer Avatar asked Jan 24 '14 01:01

Jakob Jingleheimer


1 Answers

To filter against a single type you can do:

<div ng-repeat="hash in hashes | filter: {type:'foo'}">

To filter against an array you don't need a completely custom filter but I would use a predicate filter that you can pass in to Angular's filter. Here's the filter, assuming your array type:

$scope.filterArray = function(hash) {
    return ($scope.types.indexOf(hash.type) !== -1);
};

Used like this:

<div ng-repeat="hash in hashes | filter: filterArray">

demo fiddle of both

Custom Filter

To do a completely custom filter, this works:

filter('inArray', function() {
    return function inArray( haystack , needle ) {
        var result = [];
        var item,i;
        for (i=0; i< haystack.length;i++) {
            item = haystack[i];
            if (needle.indexOf(item.type) !== -1)
              result.push(item);
        };
        return (result);
    };
});

Used like this:

<div ng-repeat="hash in hashes | inArray: types">

demo of custom filter

like image 148
KayakDave Avatar answered Oct 30 '22 18:10

KayakDave