Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Use array (multiple values) for a filter

Tags:

angularjs

I have following filter in angularJS:

<div ng-repeat="node in data | filter:{parentID:12}"></div>

This works fine (I get only data, where parentID is 12).

In the next step, I want to get all data, where parentID is (for example) 12,13,25 or 30.

I tried following (its not working):

filter:{parentID:[12,13,25,30]}

Is there any way to build a filter as described?

Thank you very much!

like image 868
Tream Avatar asked Oct 28 '14 09:10

Tream


People also ask

What is correct way to apply multiple filters in AngularJS?

Answer: A is the correct option. The syntax of applying multiple filters in AngularJS can be written as: {{ expression | filter1 | filter2 | ... }}

What is the correct way to apply filter in AngularJS?

In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for the filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope. finalResult = $filter("filter")( $scope.

Which character is used to chain multiple filters in AngularJS?

The pipe symbol ( | ) is used to chain multiple filters together.


1 Answers

A predicate function will suit your needs nicely! From the doc:

function(value, index): A predicate function can be used to write arbitrary
filters. The function is called for each element of array. The final result
is an array of those elements that the predicate returned true for.

For example:

<div ng-repeat="node in data | filter:checkParentID"></div>

And in your controller

$scope.checkParentID = function(value, index) {
  return value.parentID && [12,13,25,30].indexOf(value.parentID) !== -1;
}
like image 66
morloch Avatar answered Oct 15 '22 00:10

morloch