Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS filter comparator true while displaying ng-repeat list when input field is empty

I'm going off by this example fiddle where it demonstrates the use of comparator parameter to filter exact matches....:

http://jsfiddle.net/api/post/library/pure/

priority is a number from 1-100, but I have it input as text and filtered as string so any data that includes a substring will also pass through the ng-repeat...like when I type 1 it will also display 11, 111, 132 etc...which is how I came across the :true comparator.

I've read other stackflow answers suggesting to write custom filter functions but with the true comparator it looks like I can achieve what I want just by:

<input type="text" class="form-control" id="search.priority"
  title='Priority number to filter by'
  ng-model="search.priority" >

<tr ng-repeat="workflowItem in workflows | filter:search:true">
  <td>{{workflowItem.priority}}</td>

where it does only filter the exact matches. However, obviously it does not pass anything when the input field is empty since nothing matches the empty string.

My question is: Is there a way I can allow ng-repeat to still display everything when the field is empty while keeping the exact match filter? Appreciate everyone's time!

like image 856
ZvKa Avatar asked Jan 18 '14 03:01

ZvKa


1 Answers

You'll want to use a custom comparator function. It will allow you to perform a strict comparison except when the predicate is falsy.

Your markup would then be:

 <input type="text" class="form-control" id="search.priority"
  title='Priority number to filter by'
  ng-model="search.priority" >

<tr ng-repeat="workflowItem in workflows | filter:search:exceptEmptyComparator">
 <td>{{workflowItem.priority}}</td>

And define the comparator function on your controller:

$scope.exceptEmptyComparator = function (actual, expected) {
    if (!expected) {
       return true;
    }
    return angular.equals(expected, actual);
}

That should do the trick.

like image 86
Joel Skrepnek Avatar answered Nov 14 '22 21:11

Joel Skrepnek