javascript 如何使用 AngularJS 对多个对象应用过滤器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13834704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to apply a filter on multiple objects using AngularJS?
提问by Chubby Boy
I have the user object defined as below.
我有如下定义的用户对象。
$scope.users = [{id: 1, name: 'Adam', friends: [{name: 'John', age: 21, sex: 'M'}, {name: 'Brad', age: 32, sex: 'M'}]}]
Then I have the following code:
然后我有以下代码:
<div ng-repeat="user in users>
<input type="text" ng-model="searchText">
<div ng-repeat="friend in user.friends | filter:searchText">
{{user.name}} {{friend.name}} {{friend.age}}
</div>
</div>
Now when I type in the textbox the text: 'searchText', I want the filter to display the name of the user and the name/age of the friend. Can anyone help me with how to do this?
现在,当我在文本框中输入文本:'searchText' 时,我希望过滤器显示用户的姓名和朋友的姓名/年龄。任何人都可以帮助我如何做到这一点?
If I am correct, then I think that I need to create a custom filter for this or is there any other way I can accomplish this?
如果我是对的,那么我认为我需要为此创建一个自定义过滤器,或者还有其他方法可以实现吗?
回答by Mark Rajcok
Because you want to filter on two things at once -- some properties of the friends array and also the user -- you'll need to create your own custom filterthat accepts 2 additional parameters:
因为你想一次过滤两件事——朋友数组的一些属性和用户——你需要创建自己的自定义过滤器,它接受 2 个附加参数:
myApp.filter('myFilter', function() {
return function(friends, searchText, username) {
var searchRegx = new RegExp(searchText, "i");
if ((searchText == undefined) || (username.search(searchRegx) != -1)) {
return friends;
}
var result = [];
for(i = 0; i < friends.length; i++) {
if (friends[i].name.search(searchRegx) != -1 ||
friends[i].age.toString().search(searchText) != -1) {
result.push(friends[i]);
}
}
return result;
}
});
Then call it like so:
然后像这样调用它:
<div ng-repeat="user in users">
<input type="text" ng-model="searchText">
<div ng-repeat="friend in user.friends | myFilter:searchText:user.name">
{{user.name}} {{friend.name}} {{friend.age}}
</div>
</div>
":searchText:user.name" is the way you pass additional arguments to a custom filter.
":searchText:user.name" 是您将附加参数传递给自定义过滤器的方式。
小提琴。
回答by Umur Kontac?
http://docs.angularjs.org/api/ng.filter:filter
http://docs.angularjs.org/api/ng.filter:filter
<div ng-repeat="user in users>
<input type="text" ng-model="search.$">
<div ng-repeat="friend in user.friends | filter:search">
{{user.name}} {{friend.name}} {{friend.age}}
</div>
</div>