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') }">
The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values.
Filters can be applied to the result of another filter. This is called "chaining" and uses the following syntax: {{ expression | filter1 | filter2 | ... }} E.g. the markup {{ 1234 | number:2 }} formats the number 1234 with 2 decimal points using the number filter.
Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.
In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope. finalResult = $filter("filter")( $scope.
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' }">
I thing ng-if
should work:
<div ng-repeat="product in products" ng-if="product.color === 'red'
|| product.color === 'blue'">
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