AngularJS:过滤重复匹配列表

jac*_*cob 5 loops filter angularjs angularjs-ng-repeat

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

hashes = [
  {
      "type": "foo"
    , …
  }
  , {
      "type": "foo"
    , …
  }
  , {
      "type": "bar"
    , …
  }
]
Run Code Online (Sandbox Code Playgroud)

我想根据type它的值是否与针列表中的项匹配来过滤它们:

types = ['foo','quz'];
Run Code Online (Sandbox Code Playgroud)

所以像

<div ng-repeat="hash in hashes | filter:types"></div>
Run Code Online (Sandbox Code Playgroud)

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

Kay*_*ave 17

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

<div ng-repeat="hash in hashes | filter: {type:'foo'}">
Run Code Online (Sandbox Code Playgroud)

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

$scope.filterArray = function(hash) {
    return ($scope.types.indexOf(hash.type) !== -1);
};
Run Code Online (Sandbox Code Playgroud)

像这样使用:

<div ng-repeat="hash in hashes | filter: filterArray">
Run Code Online (Sandbox Code Playgroud)

这两个演示小提琴

定制过滤器

要执行完全自定义过滤器,这适用于:

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);
    };
});
Run Code Online (Sandbox Code Playgroud)

像这样使用:

<div ng-repeat="hash in hashes | inArray: types">
Run Code Online (Sandbox Code Playgroud)

自定义过滤器的演示