How to apply a filter on multiple objects using AngularJS?

前端 未结 2 564
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-28 23:53

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


        
2条回答
  •  醉梦人生
    2020-12-29 00:10

    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:

    {{user.name}} {{friend.name}} {{friend.age}}

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

    Fiddle.

提交回复
热议问题