Is it possible to filter an array of objects, such that the value of property can be either of a few values (OR condition) without writing a custom filter
I found a more generic solution with the most angular-native solution I can think. Basically you can pass your own comparator to the default filterFilter
function. Here's plunker as well.
I thing ng-if
should work:
<div ng-repeat="product in products" ng-if="product.color === 'red'
|| product.color === 'blue'">
In HTML:
<div ng-repeat="product in products | filter: colorFilter">
In Angular:
$scope.colorFilter = function (item) {
if (item.color === 'red' || item.color === 'blue') {
return item;
}
};
Here is a way to do it while passing in an extra argument:
https://stackoverflow.com/a/17813797/4533488 (thanks to Denis Pshenov)
<div ng-repeat="group in groups">
<li ng-repeat="friend in friends | filter:weDontLike(group.enemy.name)">
<span>{{friend.name}}</span>
<li>
</div>
With the backend:
$scope.weDontLike = function(name) {
return function(friend) {
return friend.name != name;
}
}
.
And yet another way with an in-template filter only:
https://stackoverflow.com/a/12528093/4533488 (thanks to mikel)
<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>
Best way to do this is to use a function:
<div ng-repeat="product in products | filter: myFilter">
$scope.myFilter = function (item) {
return item === 'red' || item === 'blue';
};
Alternatively, you can use ngHide or ngShow to dynamically show and hide elements based on a certain criteria.
For me, it worked as given below:
<div ng-repeat="product in products | filter: { color: 'red'||'blue' }">
<div ng-repeat="product in products | filter: { color: 'red'} | filter: { color:'blue' }">