如何使用 AngularJS 对多个对象应用过滤器? [英] How to apply a filter on multiple objects using AngularJS?

查看:35
本文介绍了如何使用 AngularJS 对多个对象应用过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下定义的用户对象.

$scope.users = [{id: 1, name: 'Adam', Friends: [{name: 'John', age: 21, sex: 'M'}, {name: 'Brad',年龄:32,性别:'M'}]}]

然后我有以下代码:

现在,当我在文本框中输入文本:searchText"时,我希望过滤器显示用户的姓名和朋友的姓名/年龄.任何人都可以帮助我如何做到这一点?

如果我是对的,那么我认为我需要为此创建一个自定义过滤器,或者还有其他方法可以做到这一点吗?

解决方案

因为你想同时过滤两件事——friends 数组的一些属性和用户——你需要创建自己的<接受 2 个附加参数的 href="http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters">自定义过滤器:

myApp.filter('myFilter', function() {返回函数(朋友,搜索文本,用户名){var searchRegx = new RegExp(searchText, "i");if ((searchText == undefined) || (username.search(searchRegx) != -1)) {回访朋友;}var 结果 = [];for(i = 0; i 

然后这样称呼它:

<input type="text" ng-model="searchText"><div ng-repeat="friend in user.friends | myFilter:searchText:user.name">{{user.name}} {{friend.name}} {{friend.age}}

":searchText:user.name" 是您向自定义过滤器传递附加参数的方式.

小提琴.

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?

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?

解决方案

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 filter that accepts 2 additional parameters:

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.

Fiddle.

这篇关于如何使用 AngularJS 对多个对象应用过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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