AngularJS filter only on certain objects

Chubby Boy picture Chubby Boy · Dec 11, 2012 · Viewed 21.6k times · Source

I have the user object defined as below.

$scope.user = [{id: 1, friends:
    [
        {name: 'John', age: 21, sex: 'M'},
        {name: 'Brad', age: 32, sex: 'M'}
    ]
}]

I have the following code:

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

Here whenever I search, I get results for name, age as well as sex. But I want to search only for name and age and I don't want sex to be searchable. Can anyone help me with how I can achieve this?

Answer

ricick picture ricick · Dec 11, 2012

You can pass an object as the second parameter to achieve this if you can have two search fields

<div ng-repeat="friend in user.friends | filter:{name:searchNameText, age:searchAgeText}">

Otherwise you'll need to write a custom filter to use the same field for both, or pass a custom filter function as the third parameter which is described in the docs.

http://docs.angularjs.org/api/ng.filter:filter