How to filter multiple values (OR operation) in angularJS

前端 未结 20 1297
清酒与你
清酒与你 2020-11-22 10:01

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

20条回答
  •  我在风中等你
    2020-11-22 10:20

    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:

  • {{x.name}}
提交回复
热议问题