关于angularjs中filter问题

<li ng-repeat="phone in phones|filter:query">

一般都是这样写过滤,但是我想只针对一部分数据,phone.name实现过滤这个要如何实现呢??

阅读 4.1k
3 个回答

<li ng-repeat="phone in phones|filter:{'name': query}">

根据官方文档的描述,有几种方式来实现:
{{ filter_expression | filter : expression : comparator}}

1.如Guox给出的方法,使用expression:

Object: A pattern object can be used to filter specific properties on objects contained by array. For example {name:"M", phone:"1"} predicate will return an array of items which have property name containing "M" and property phone containing "1".

作为Object使用,用于过滤数组元素的指定属性,如expression = {name:"M", phone:"1"} ,那么将会过滤出数组中name包含'M'且phone包含'1'的元素。

故使用如下方法即可

<li ng-repeat="phone in phones|filter:{name:query}">

2.可以使用comparator:

Comparator which is used in determining if the expected value (from the filter expression) and actual value (from the object in the array) should be considered a match.
function(actual, expected): The function will be given the object value and the predicate value to compare and should return true if both values should be considered equal.

通过Comparator的返回值能够决定是否匹配,入参分别是actual(数组中的元素)和expected(输入)

那么定义一个函数

$scope.customerFilter = customerFilter;

function customerFilter(actual, expected){
    return actual.name.contains(expexted) ? true : false;
}

前端使用
<li ng-repeat="phone in phones|filter:query:customerFilter">

太感谢二位了,谢谢

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进