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

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

问题描述

我的用户对象定义如下。

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'}]}]

然后我有以下代码:

<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>

现在当我在文本框中键入文本:'searchText'时,我希望过滤器显示名称用户和朋友的姓名/年龄。任何人都可以帮我解决这个问题吗?

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?

推荐答案

因为你想过滤两件事曾经 - 朋友阵列的一些属性以及用户 - 您需要创建自己的自定义过滤,接受2个额外参数:

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;
  }
});

然后如下调用:

<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是您将其他参数传递给自定义过滤器的方式。

":searchText:user.name" is the way you pass additional arguments to a custom filter.

小提琴

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

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