How to filter multiple values (OR operation) in an

2018-12-31 10:05发布

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()...

20条回答
几人难应
2楼-- · 2018-12-31 10:52

My solution

ng-repeat="movie in movies | filter: {'Action'} + filter: {'Comedy}"
查看更多
柔情千种
3楼-- · 2018-12-31 10:53

I wrote this for strings AND functionality (I know it's not the question but I searched for it and got here), maybe it can be expanded.

String.prototype.contains = function(str) {
  return this.indexOf(str) != -1;
};

String.prototype.containsAll = function(strArray) {
  for (var i = 0; i < strArray.length; i++) {
    if (!this.contains(strArray[i])) {
      return false;
    }
  }
  return true;
}

app.filter('filterMultiple', function() {
  return function(items, filterDict) {
    return items.filter(function(item) {
      for (filterKey in filterDict) {
        if (filterDict[filterKey] instanceof Array) {
          if (!item[filterKey].containsAll(filterDict[filterKey])) {
            return false;
          }
        } else {
          if (!item[filterKey].contains(filterDict[filterKey])) {
            return false;
          }
        }
      }
      return true;
    });  
  };
});

Usage:

<li ng-repeat="x in array | filterMultiple:{key1: value1, key2:[value21, value22]}">{{x.name}}</li>
查看更多
登录 后发表回答