How to apply a filter on multiple objects using AngularJS?

▼魔方 西西 提交于 2019-11-30 04:02:14

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.

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!