AngularJS strict filter on only one field

Syl picture Syl · Jul 21, 2014 · Viewed 21.4k times · Source

I have a form with multiple filters but for some, I need a strict comparison.

tl;dr: strict comparison for user_id not for firstname.

<select ng-model="search.user_id">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="10">10</option>
    <option value="11">11</option>
    <option value="23">23</option>
</select>

<input type="text" ng-model="search.firstname">

<ul>
    <li ng-repeat="user in users | filter:search">#{{ user.user_id }} {{ user.firstname}}</li>
</ul>

I tried the third parameter true but it also works for firstname filter.

The problem is: if you select the value 2, all users with a 2 in their id will be filtered, I don't want this behavior.

Here is the fiddle.

Answer

harishr picture harishr · Jul 21, 2014

i have tried to fix it natively, rather than with custom filters, its working, here's the PLUNKER LINK

had to specify multiple filters tag

<li ng-repeat="user in users | filter:{'user_id':  search.user_id}: true | filter: {'firstname' : search.firstname}">

though there are few caveats:

  1. i had to change the type from number to string...

  2. if i reset the value of exact match it doesnt work...

so then i had to write a custom filer which works for exact match & ignores empty/null values

$scope.filter2 = function(field1, field2) {
  if(field2 === "" || field2 === null) return true;
  return field1 === field2;
};

you would find both of them in the provided plunker link