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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With