Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
AngularJS:根据列表筛选重复匹配_Angularjs_Loops_Filter_Angularjs Ng Repeat - Fatal编程技术网

AngularJS:根据列表筛选重复匹配

AngularJS:根据列表筛选重复匹配,angularjs,loops,filter,angularjs-ng-repeat,Angularjs,Loops,Filter,Angularjs Ng Repeat,我有一个被ngRepeat循环的对象列表: hashes = [ { "type": "foo" , … } , { "type": "foo" , … } , { "type": "bar" , … } ] 如果其值与针列表中的项目匹配,我想根据类型对其进行过滤: types = ['foo','quz']; 大概是 <div ng-repeat="hash in hashes | filter:ty

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

hashes = [
  {
      "type": "foo"
    , …
  }
  , {
      "type": "foo"
    , …
  }
  , {
      "type": "bar"
    , …
  }
]
如果其值与针列表中的项目匹配,我想根据
类型对其进行过滤:

types = ['foo','quz'];
大概是

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


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

要针对单个类型进行过滤,可以执行以下操作:

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

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

两者的

自定义过滤器

要执行完全自定义的过滤器,请执行以下操作:

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);
    };
});
过滤器('inArray',函数(){
返回函数INARAY(草堆、针){
var结果=[];
var项目,i;
对于(i=0;i
这样使用:

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


我最终将其制作成一个名为inArray的合适过滤器(即à;la php's in_array)。将其添加到我问题的底部。@jacob您确定过滤器对您正常工作吗?通常,自定义筛选器希望返回一个包含所有传递值的数组(与谓词筛选器不同,谓词筛选器是基于每个条目执行的)-但似乎您返回的是布尔值。啊,这解释了为什么指针是传递给ngRepeat的整个数组,而不是我指定的属性。我们可以将此筛选器与集合的特定属性一起使用吗?