Yogesh Mangaj Yogesh Mangaj - 3 months ago 32
AngularJS Question

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

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

This is similar to this problem - Angular.js ng-repeat :filter by single field

But instead of

<div ng-repeat="product in products | filter: { color: 'red' }">


is it possible to do something like this

<div ng-repeat="product in products | filter: { color: 'red'||'blue' }">


for a sample data as follows-

$scope.products = [
{ id: 1, name: 'test', color: 'red' },
{ id: 2, name: 'bob', color: 'blue' }
/*... etc... */
];


I've unsuccessfully tried

<div ng-repeat="product in products | filter: { color: ('red'||'blue') }">

Answer

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.

Comments