简体   繁体   中英

ng-repeat filter with OR condition of property

I wanted to filter a list with a model value from the text box.

Example

 var person={};
 person.Id=1;
 person.Name="Test 1";
 person.PetName="Rest 1"

 var persons=[];
 persons.push(person);

 person.Id=2;
 person.Name="Test ds";
 person.PetName="Rest sd";
 persons.push(person);

Persons array will have multiple persons. In HTML I have one search box.

<input type="text" ng-model="seachText" placeholder="search by Name and pet name"/>

<div ng-repeat="person in persons | filter : {$:seachText}">
<div>{{person.Name}}</div>
</div>

Case 1:

When I enter 2 in the text box, one result will appear. I don't want that. I want to filter by name and pet-name only.

Is there any possibility to achieve this without a custom filter? Does filter directive allow OR condition for properties?

Please help. Thanks.

For me custom "OR" filter is preferred solution, nevertheless you can use built-in filter two times(for each OR condition) and then UNION ALL results:

 angular.module('app', []).controller('ctrl', function($scope){ $scope.persons = [ {Id:95, Name:"Tom", PetName: "Pet1"}, {Id:96, Name:"Sam", PetName: "Pet2"}, {Id:97, Name:"Max", PetName: "Pet3"}, {Id:98, Name:"Henry", PetName: "Pet4"} ] })
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app='app' ng-controller='ctrl'> <input type='text' ng-model='search'/> <div ng-repeat='person in temp = (persons | filter : {Name: search})'> {{person | json}} </div> <div ng-repeat='person in persons | filter : {PetName: search}' ng-if='temp.indexOf(person) == -1'> {{person | json}} </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM