136

我想使用filterin 角度并希望过滤多个值,如果它具有其中一个值,则应该显示它。

例如,我有这个结构:

movie一个具有属性的对象,genres我想过滤ActionComedy

我知道我可以做filter:({genres: 'Action'} || {genres: 'Comedy'}),但是如果我想动态过滤它怎么办。例如filter: variableX

当我有一系列必须过滤的类型时,如何在 中设置variableX$scope

我可以将它构造为一个字符串,然后做一个eval()但我不想使用 eval()...

4

20 回答 20

88

我只想创建一个自定义过滤器。他们没有那么难。

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

模板:

<h1>Movies</h1>

<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}}
<ul>
    <li ng-repeat="movie in movies | bygenre:genrefilters">{{movie.title}}: {{movie.genre}}</li>
</ul>

在此处编辑是链接:创建角度过滤器

更新:这是一个小提琴,其中包含我的建议的精确演示。

于 2013-04-08T00:16:00.567 回答
82

您可以使用控制器功能进行过滤。

function MoviesCtrl($scope) {

    $scope.movies = [{name:'Shrek', genre:'Comedy'},
                     {name:'Die Hard', genre:'Action'},
                     {name:'The Godfather', genre:'Drama'}];

    $scope.selectedGenres = ['Action','Drama'];

    $scope.filterByGenres = function(movie) {
        return ($scope.selectedGenres.indexOf(movie.genre) !== -1);
    };

}

HTML:

<div ng-controller="MoviesCtrl">
    <ul>
        <li ng-repeat="movie in movies | filter:filterByGenres">
            {{ movie.name }} {{ movie.genre }}
        </li>
    </ul>
</div>
于 2013-04-08T00:53:37.397 回答
24

在这里创建自定义过滤器可能有点过头了,你可以传入一个自定义比较器,如果你有多个值,比如:

$scope.selectedGenres = "Action, Drama"; 

$scope.containsComparator = function(expected, actual){  
  return actual.indexOf(expected) > -1;
};

然后在过滤器中:

filter:{name:selectedGenres}:containsComparator
于 2013-09-03T14:09:55.173 回答
18

这是自定义过滤器的实现,它将使用值数组过滤数据。它将支持具有数组和单个键值的多个键对象。如前所述,inangularJS API AngularJS 过滤器文档支持单个值的多个键过滤器,但下面的自定义过滤器将支持与 angularJS 相同的功能,并且还支持值数组以及数组和键值的组合。请在下面找到代码片段,

myApp.filter('filterMultiple',['$filter',function ($filter) {
return function (items, keyObj) {
    var filterObj = {
        data:items,
        filteredData:[],
        applyFilter : function(obj,key){
            var fData = [];
            if (this.filteredData.length == 0)
                this.filteredData = this.data;
            if (obj){
                var fObj = {};
                if (!angular.isArray(obj)){
                    fObj[key] = obj;
                    fData = fData.concat($filter('filter')(this.filteredData,fObj));
                } else if (angular.isArray(obj)){
                    if (obj.length > 0){
                        for (var i=0;i<obj.length;i++){
                            if (angular.isDefined(obj[i])){
                                fObj[key] = obj[i];
                                fData = fData.concat($filter('filter')(this.filteredData,fObj));    
                            }
                        }

                    }
                }
                if (fData.length > 0){
                    this.filteredData = fData;
                }
            }
        }
    };
    if (keyObj){
        angular.forEach(keyObj,function(obj,key){
            filterObj.applyFilter(obj,key);
        });
    }
    return filterObj.filteredData;
}
}]);

用法:

arrayOfObjectswithKeys | filterMultiple:{key1:['value1','value2','value3',...etc],key2:'value4',key3:[value5,value6,...etc]}

这是一个实现上述“filterMutiple”自定义过滤器的小提琴示例。 :::小提琴示例:::

于 2014-01-16T18:10:47.403 回答
14

如果你想过滤对象数组,那么你可以给

filter:({genres: 'Action', key :value }.

单个属性将由为该属性指定的特定过滤器过滤。

但是,如果您想按单个属性进行过滤并针对所有属性进行全局过滤,那么您可以执行类似的操作。

<tr ng-repeat="supp in $data | filter : filterObject |  filter : search">
其中“filterObject”是用于搜索单个属性的对象,“Search”将在全局范围内搜索每个属性。

~阿图尔

于 2014-09-18T18:14:15.183 回答
9

我花了一些时间,感谢@chrismarx,我看到 angular 的默认设置filterFilter允许您传递自己的比较器。这是多个值的编辑比较器:

  function hasCustomToString(obj) {
        return angular.isFunction(obj.toString) && obj.toString !== Object.prototype.toString;
  }
  var comparator = function (actual, expected) {
    if (angular.isUndefined(actual)) {
      // No substring matching against `undefined`
      return false;
    }
    if ((actual === null) || (expected === null)) {
      // No substring matching against `null`; only match against `null`
      return actual === expected;
    }
    // I edited this to check if not array
    if ((angular.isObject(expected) && !angular.isArray(expected)) || (angular.isObject(actual) && !hasCustomToString(actual))) {
      // Should not compare primitives against objects, unless they have custom `toString` method
      return false;
    }
    // This is where magic happens
    actual = angular.lowercase('' + actual);
    if (angular.isArray(expected)) {
      var match = false;
      expected.forEach(function (e) {
        e = angular.lowercase('' + e);
        if (actual.indexOf(e) !== -1) {
          match = true;
        }
      });
      return match;
    } else {
      expected = angular.lowercase('' + expected);
      return actual.indexOf(expected) !== -1;
    }
  };

如果我们想为 DRY 制作一个自定义过滤器:

angular.module('myApp')
    .filter('filterWithOr', function ($filter) {
      var comparator = function (actual, expected) {
        if (angular.isUndefined(actual)) {
          // No substring matching against `undefined`
          return false;
        }
        if ((actual === null) || (expected === null)) {
          // No substring matching against `null`; only match against `null`
          return actual === expected;
        }
        if ((angular.isObject(expected) && !angular.isArray(expected)) || (angular.isObject(actual) && !hasCustomToString(actual))) {
          // Should not compare primitives against objects, unless they have custom `toString` method
          return false;
        }
        console.log('ACTUAL EXPECTED')
        console.log(actual)
        console.log(expected)

        actual = angular.lowercase('' + actual);
        if (angular.isArray(expected)) {
          var match = false;
          expected.forEach(function (e) {
            console.log('forEach')
            console.log(e)
            e = angular.lowercase('' + e);
            if (actual.indexOf(e) !== -1) {
              match = true;
            }
          });
          return match;
        } else {
          expected = angular.lowercase('' + expected);
          return actual.indexOf(expected) !== -1;
        }
      };
      return function (array, expression) {
        return $filter('filter')(array, expression, comparator);
      };
    });

然后我们可以在任何我们想要的地方使用它:

$scope.list=[
  {name:'Jack Bauer'},
  {name:'Chuck Norris'},
  {name:'Superman'},
  {name:'Batman'},
  {name:'Spiderman'},
  {name:'Hulk'}
];


<ul>
  <li ng-repeat="item in list | filterWithOr:{name:['Jack','Chuck']}">
    {{item.name}}
  </li>
</ul>

最后这是一个plunkr

注意:预期的数组应该只包含简单的对象,如StringNumber等。

于 2015-06-23T15:06:59.293 回答
7

您可以使用 angular.filter 的 searchField 过滤

JS:

$scope.users = [
 { first_name: 'Sharon', last_name: 'Melendez' },
 { first_name: 'Edmundo', last_name: 'Hepler' },
 { first_name: 'Marsha', last_name: 'Letourneau' }
];

HTML:

<input ng-model="search" placeholder="search by full name"/> 
<th ng-repeat="user in users | searchField: 'first_name': 'last_name' | filter: search">
  {{ user.first_name }} {{ user.last_name }}
</th>
<!-- so now you can search by full name -->
于 2014-07-23T06:54:05.503 回答
7

ngIf如果情况允许,您也可以使用:

<div ng-repeat="p in [
 { name: 'Justin' }, 
 { name: 'Jimi' }, 
 { name: 'Bob' }
 ]" ng-if="['Jimi', 'Bob'].indexOf(e.name) > -1">
 {{ p.name }} is cool
</div>
于 2015-09-28T19:56:47.927 回答
7

The quickest solution that I've found is to use the filterBy filter from angular-filter, for example:

<input type="text" placeholder="Search by name or genre" ng-model="ctrl.search"/>   
<ul>
  <li ng-repeat="movie in ctrl.movies | filterBy: ['name', 'genre']: ctrl.search">
    {{movie.name}} ({{movie.genre}}) - {{movie.rating}}
  </li>
</ul>

The upside is that angular-filter is a fairly popular library (~2.6k stars on GitHub) which is still actively developed and maintained, so it should be fine to add it to your project as a dependency.

于 2016-09-09T23:18:37.353 回答
4

我相信这就是您正在寻找的:

<div>{{ (collection | fitler1:args) + (collection | filter2:args) }}</div>
于 2014-07-11T14:17:32.217 回答
2

假设您有两个数组,一个用于电影,一个用于流派

只需将过滤器用作:filter:{genres: genres.type}

这里的流派是数组,类型对流派有价值

于 2015-03-11T19:48:16.867 回答
2

请试试这个

var m = angular.module('yourModuleName');
m.filter('advancefilter', ['$filter', function($filter){
    return function(data, text){
        var textArr = text.split(' ');
        angular.forEach(textArr, function(test){
            if(test){
                  data = $filter('filter')(data, test);
            }
        });
        return data;
    }
}]);
于 2015-06-24T10:51:58.397 回答
1

我为字符串和功能编写了这个(我知道这不是问题,但我搜索并到了这里),也许它可以扩展。

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;
    });  
  };
});

用法:

<li ng-repeat="x in array | filterMultiple:{key1: value1, key2:[value21, value22]}">{{x.name}}</li>
于 2014-10-30T01:02:09.637 回答
1

角度或过滤器模块

$filter('orFilter')([{..}, {..} ...], {arg1, arg2, ...}, false)

这是链接:https ://github.com/webyonet/angular-or-filter

于 2014-12-10T14:09:18.743 回答
1

我有类似的情况。编写自定义过滤器对我有用。希望这可以帮助!

JS:

App.filter('searchMovies', function() {
    return function (items, letter) {
        var resulsts = [];
        var itemMatch = new RegExp(letter, 'i');
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            if ( itemMatch.test(item.name) || itemMatch.test(item.genre)) {
                results.push(item);
            }
        }
        return results;
    };
});

HTML:

<div ng-controller="MoviesCtrl">
    <ul>
        <li ng-repeat="movie in movies | searchMovies:filterByGenres">
            {{ movie.name }} {{ movie.genre }}
        </li>
    </ul>
</div>
于 2015-06-30T18:57:50.343 回答
1

这是我的示例如何为表jsfiddle创建过滤器和指令

指令获取列表(数据)并使用过滤器创建表

<div ng-app="autoDrops" ng-controller="HomeController">
<div class="row">
    <div class="col-md-12">
        <h1>{{title}}</h1>
        <ng-Multiselect array-List="datas"></ng-Multiselect>
    </div>
</div>
</div>

如果我能帮助你,我很高兴

于 2016-08-08T10:17:53.393 回答
1

Too late to join the party but may be it can help someone:

We can do it in two step, first filter by first property and then concatenate by second filter:

$scope.filterd = $filter('filter')($scope.empList, { dept: "account" });
$scope.filterd = $scope.filterd.concat($filter('filter')($scope.empList, { dept: "sales" }));  

See the working fiddle with multiple property filter

于 2017-05-24T20:19:42.727 回答
0

OPTION 1: Using Angular providered filter comparator parameter

// declaring a comparator method
$scope.filterBy = function(actual, expected) {
    return _.contains(expected, actual); // uses underscore library contains method
};

var employees = [{name: 'a'}, {name: 'b'}, {name: 'c'}, {name: 'd'}];

// filter employees with name matching with either 'a' or 'c'
var filteredEmployees = $filter('filter')(employees, {name: ['a','c']}, $scope.filterBy);

OPTION 2: Using Angular providered filter negation

var employees = [{name: 'a'}, {name: 'b'}, {name: 'c'}, {name: 'd'}];

// filter employees with name matching with either 'a' or 'c'
var filteredEmployees = $filter('filter')($filter('filter')(employees, {name: '!d'}), {name: '!b'});
于 2018-12-28T18:38:10.273 回答
-3

我的解决方案

ng-repeat="movie in movies | filter: {'Action'} + filter: {'Comedy}"
于 2015-06-18T17:45:34.497 回答
-14

最好的答案是:

filter:({genres: 'Action', genres: 'Comedy'}
于 2014-03-21T09:09:34.693 回答