AngularJS:过滤重复匹配列表

时间:2014-01-24 01:25:13

标签: angularjs loops filter angularjs-ng-repeat

我有一个由ngRepeat环绕的对象列表:

hashes = [
  {
      "type": "foo"
    , …
  }
  , {
      "type": "foo"
    , …
  }
  , {
      "type": "bar"
    , …
  }
]

如果它的值与针列表中的项匹配,我想根据type过滤它们:

types = ['foo','quz'];

类似

<div ng-repeat="hash in hashes | filter:types"></div>

这是内置到Angular还是我必须编写自定义过滤器?

1 个答案:

答案 0 :(得分:17)

要过滤单一类型,您可以执行以下操作:

<div ng-repeat="hash in hashes | filter: {type:'foo'}">

要过滤数组,您不需要完全自定义的过滤器,但我会使用谓词过滤器,您可以将其传递给Angular的过滤器。这是过滤器,假设您的数组为type

$scope.filterArray = function(hash) {
    return ($scope.types.indexOf(hash.type) !== -1);
};

像这样使用:

<div ng-repeat="hash in hashes | filter: filterArray">

demo fiddle

自定义过滤器

要完成自定义过滤器,可以使用:

filter('inArray', function() {
    return function inArray( haystack , needle ) {
        var result = [];
        var item,i;
        for (i=0; i< haystack.length;i++) {
            item = haystack[i];
            if (needle.indexOf(item.type) !== -1)
              result.push(item);
        };
        return (result);
    };
});

像这样使用:

<div ng-repeat="hash in hashes | inArray: types">

demo of custom filter