Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply a filter on multiple objects using 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'}]}]

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?

like image 432
Chubby Boy Avatar asked Dec 12 '12 07:12

Chubby Boy


2 Answers

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.

like image 199
Mark Rajcok Avatar answered Nov 13 '22 19:11

Mark Rajcok


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>
like image 38
Umur Kontacı Avatar answered Nov 13 '22 21:11

Umur Kontacı