AngularJS filter only on certain objects

不想你离开。 提交于 2019-12-03 00:25:36

I'm not sure if this is what you are after. If you want to have one input field to matched multiple properties you need a filter function to be passed to filter.

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

$scope.searchFilter = function (obj) {
    var re = new RegExp($scope.searchText, 'i');
    return !$scope.searchText || re.test(obj.name) || re.test(obj.age.toString());
};

Here's a fiddle example http://jsfiddle.net/fredrik/26fZb/1/

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

This is not the cleanest way to accomplish what you want, but it is the simplest way to accomplish an OR filter using the standard ng-repeat filter.

Controller:

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

$scope.buildSearchData = buildSearchData;

function buildSearchData(friend){
    return friend.name + ' ' + friend.age;
}

HTML

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

"friend in user.friends | json | filter:{something:somethingtext}"

http://docs-angularjs-org-dev.appspot.com/api/ng.filter:json

Another possible approach is to create an aggregate field that contains the values of all of the fields you want to filter on concatenated and only filter on that.

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