1

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.

Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
Vivek Verma
  • 293
  • 3
  • 16
  • `persons` will have two identical objects because you're making changes in and pushing the same object twice. – 31piy Feb 05 '18 at 09:30
  • https://stackoverflow.com/questions/13216115/filtering-by-multiple-specific-model-properties-in-angularjs-in-or-relationship – Marcus Höglund Feb 05 '18 at 09:31
  • No.. am re using same object. Anyways thats not an issue. Assume an array with multiple records and you have to search with few property with same model value – Vivek Verma Feb 05 '18 at 09:32
  • Thanks Marcus, that will work, but it is custom filter – Vivek Verma Feb 05 '18 at 09:33

1 Answers1

1

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>
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26
  • Thanks :) I was just looking for answer whether OR condition exists within inbuilt filter. I guess not, so I have taken custom filter approach. – Vivek Verma Feb 12 '18 at 17:49