I want to use the filter
in angular and want to filter for multiple values, if it has either one of the values then it should be displayed.
I have for example this structure:
An object movie
which has the property genres
and I want to filter for Action
and Comedy
.
I know I can do filter:({genres: 'Action'} || {genres: 'Comedy'})
, but what to do if I want to filter it dynamically. E.g. filter: variableX
How do I set variableX
in the $scope
, when I have an array of the genres I have to filter?
I could construct it as a string and then do an eval()
but I don't want to use eval()...
I would just create a custom filter. They are not that hard.
template:
Edit here is the link: Creating Angular Filters
UPDATE: Here is a fiddle that has an exact demo of my suggestion.
OPTION 1: Using Angular providered filter comparator parameter
OPTION 2: Using Angular providered filter negation
I've spent some time on it and thanks to @chrismarx, I saw that angular's default
filterFilter
allows you to pass your own comparator. Here's the edited comparator for multiple values:And if we want to make a custom filter for DRY:
And then we can use it anywhere we want:
Finally here's a plunkr.
Note: Expected array should only contain simple objects like String, Number etc.
Creating a custom filter might be overkill here, you can just pass in a custom comparator, if you have the multiples values like:
then in the filter:
you can use searchField filter of angular.filter
JS:
HTML:
Please try this