AngularJS:对列表过滤重复的比赛 [英] AngularJS: filter repeat match against list
问题描述
我有得到由ngRepeat环绕在对象列表:
I have a list of objects that gets looped over by ngRepeat:
hashes = [
{
"type": "foo"
, …
}
, {
"type": "foo"
, …
}
, {
"type": "bar"
, …
}
]
我要基于对它们进行过滤键入
,如果它是一个值项针的匹配列表:
I want to filter them based on type
if it's value matches a item in a list of needles:
types = ['foo','quz'];
所以像
<div ng-repeat="hash in hashes | filter:types"></div>
这是内置到角或者我会写一个自定义过滤器?
Is this built into Angular or would I have to write a custom filter?
推荐答案
要筛选针对单一类型的,你可以这样做:
To filter against a single type you can do:
<div ng-repeat="hash in hashes | filter: {type:'foo'}">
要筛选对数组你不需要完全自定义的过滤器,但我会用predicate过滤器,你可以在传递到角的过滤器。这里的过滤器,假设你的阵列键入
:
To filter against an array you don't need a completely custom filter but I would use a predicate filter that you can pass in to Angular's filter. Here's the filter, assuming your array type
:
$scope.filterArray = function(hash) {
return ($scope.types.indexOf(hash.type) !== -1);
};
用于这样的:
<div ng-repeat="hash in hashes | filter: filterArray">
自定义过滤器
要做到完全自定义过滤器,这个作品:
To do a completely custom filter, this works:
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">
自定义过滤器的演示
这篇关于AngularJS:对列表过滤重复的比赛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!