AngularJS 自定义过滤功能 [英] AngularJS custom filter function
问题描述
在我的控制器中,我想过滤一组对象.这些对象中的每一个都是一个可以包含字符串和列表的映射
我尝试使用 $filter('filter')(array, function)
格式,但我不知道如何在我的函数中访问数组的各个元素.这是显示我想要的内容的片段.
$filter('filter')(array, function() {返回标准匹配(项目,标准);});
然后在 criteriaMatch()
中,我将检查每个属性是否匹配
var criteriaMatch = function(item, criteria) {//遍历项目和条件中的每个单独的属性//并检查它们是否相等}
我必须在控制器中完成所有这些并编译一个列表列表并将它们设置在范围内.所以我只需要通过这种方式访问 $filter('filter')
.到目前为止,我在网上找到的所有示例都在函数内部进行了静态条件搜索,它们不传递条件对象并针对数组中的每个项目进行测试.
你可以这样使用:http://plnkr.co/edit/vtNjEgmpItqxX5fdwtPi?p=preview
就像你发现的那样,filter
接受谓词函数,它接受项按数组中的项.因此,您只需要根据给定的 criteria
创建一个谓词函数.
在这个例子中,criteriaMatch
是一个返回谓词的函数匹配给定criteria
的函数.
模板:
{{ 物品 }}
范围:
$scope.criteriaMatch = 函数(标准){返回函数(项目){返回 item.name === criteria.name;};};
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
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);
});
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
}
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.
You can use it like this: http://plnkr.co/edit/vtNjEgmpItqxX5fdwtPi?p=preview
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
.
In this example, criteriaMatch
is a function which returns a predicate
function which matches the given criteria
.
template:
<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
{{ item }}
</div>
scope:
$scope.criteriaMatch = function( criteria ) {
return function( item ) {
return item.name === criteria.name;
};
};
这篇关于AngularJS 自定义过滤功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!