AngularJS自定义滤镜功能 [英] AngularJS custom filter function

查看:284
本文介绍了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

我试着用 $过滤器('过滤器')(数组功能)的格式,但我不知道如何访问我的函数内部数组的单个元素。下面是一个片段,以显示我想要的东西。

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
}

我必须做的所有这些控制器和编译列表的列表,并设置它们的范围。所以,我需要访问 $过滤器('过滤器')只能这样。我在网上找到的所有的例子都在函数内部静态标准的搜索,他们并不在数组中传递对每个项目的标准,对象和测试。

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.

推荐答案

您可以使用它像这样:
<一href=\"http://plnkr.co/edit/vtNjEgmpItqxX5fdwtPi?p=$p$pview\">http://plnkr.co/edit/vtNjEgmpItqxX5fdwtPi?p=$p$pview

就像你发现了,过滤接受它接受项目predicate功能
通过从数组项。
所以,你只需要创建一个基于给定的标准的predicate功能

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 是返回和predicate功能
函数匹配给定标准

In this example, criteriaMatch is a function which returns and 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;
  };
};

这篇关于AngularJS自定义滤镜功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆