JustGoscha JustGoscha - 1 year ago 118
AngularJS Question

How to filter multiple values (OR operation) in angularJS

I want to use the

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
which has the property
and I want to filter for

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
in the
, when I have an array of the genres I have to filter?

I could construct it as a string and then do an
but I don't want to use eval()...

Answer Source

I would just create a custom filter. They are not that hard.

angular.module('myFilters', []).
  filter('bygenre', function() {
    return function(movies,genres) {
      var out = [];
      // Filter logic here, adding matches to the out var.
      return out;



<div ng-init="movies = [
          {title:'Man on the Moon', genre:'action'},
          {title:'Meet the Robinsons', genre:'family'},
          {title:'Sphere', genre:'action'}
       ];" />
<input type="checkbox" ng-model="genrefilters.action" />Action
<br />
<input type="checkbox" ng-model="genrefilters.family" />Family
<br />{{genrefilters.action}}::{{genrefilters.family}}
    <li ng-repeat="movie in movies | bygenre:genrefilters">{{movie.title}}: {{movie.genre}}</li>

Edit here is the link: Creating Angular Filters

UPDATE: Here is a fiddle that has an exact demo of my suggestion.