AngularJS自定义过滤器功能
在我的控制器中,我想过滤一个对象数组。每个这些对象是一个可以包含字符串以及列表的映射
Inside my controller, I would like to filter an array of objects. Each of these objects is a map which can contain strings as well as lists
我尝试使用 $ filter('filter') )
格式,但我不知道如何访问我的函数内的数组的单个元素。这是一个代码片段来显示我想要的。
I tried using $filter('filter')(array, function)
format but I do not know how to access the individual elements of the array inside my function. Here is a snippet to show what I want.
$filter('filter')(array, function() {
return criteriaMatch(item, criteria);
});
然后在 criteriaMatch()
我会检查每个个体属性是否匹配
And then in the criteriaMatch()
, I will check if each of the individual property matches
var criteriaMatch = function(item, criteria) {
// go thro each individual property in the item and criteria
// and check if they are equal
}
b $ b
我必须在控制器中做所有这些,并编译列表的列表,并将其设置在范围内。所以我需要以这种方式访问 $ filter('filter')
。我在网络中找到的所有示例在函数中都有静态条件搜索,它们不通过一个标准对象,并对数组中的每个项目进行测试。
I have to do all these in the controller and compile a list of lists and set them in the scope. So I do need to access the $filter('filter')
this way only. All the examples I found in the net so far have static criteria searches inside the function, they don't pass an criteria object and test against each item in the array.
您可以这样使用它:
http://plnkr.co / edit / vtNjEgmpItqxX5fdwtPi?p = preview
像你发现的, filter
接受谓词函数, item
从数组中的项。
所以,你只需要根据给定的条件$ c>创建一个谓词函数。
Like you found, filter
accepts predicate function which accepts item
by item from the array.
So, you just have to create an predicate function based on the given criteria
.
例如, criteriaMatch
是返回与给定的条件
匹配的谓词
函数的函数。
In this example, criteriaMatch
is a function which returns a predicate
function which matches the given criteria
.
模板:
<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
{{ item }}
</div>
范围:
$scope.criteriaMatch = function( criteria ) {
return function( item ) {
return item.name === criteria.name;
};
};