Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS strict filter on only one field

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.

like image 735
Syl Avatar asked Jul 21 '14 14:07

Syl


1 Answers

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

like image 187
harishr Avatar answered Sep 22 '22 09:09

harishr