bigbearzhu bigbearzhu - 5 months ago 206x
AngularJS Question

Angular function filter comparator example

Can someone give me an example of how to use Angular filter comparator?

From official doc:

function(actual, expected): The function will be given the object value and the predicate value to compare and should return true if the item should be included in filtered result.

There is a great blog post talking about Angular filter:
Fun with AngularJS filters - Part 1: the

However, at the end of it, where I am looking for some useful example of the function comparator, I still found nothing.

For more particular matching needs, you can pass a function instead of a boolean as the comparator argument.

I have tried few combinations by myself. Neither adding the function at the end of the expression or pointing to a function in scope do the work.


I did something like this, since Angular iterates on objects and tries to compare them whole as well as recursively their individual properties.

// in your controller
$scope.filterMyData = function (input, search_param) {
  if (input && input.propertyWeCareAbout) {
    // it's ugly, but to quickly get something done you can ignore search_param 
    return input.propertyWeCareAbout === $scope.SomeOtherData;
  else {
    return angular.equals(input, search_param);
<span>Quick search: </span><input type="search" ng-model='quickSearch'/><br/>

  <tr ng-repeat="obj in someHttpService.dataAsArray | filter:quickSearch:filterMyData">
    <td>{{ obj.key }} </td>
    <td>{{ obj.propertyWeCareAbout }}</td>

In my case, "quickSearch" is largely meaningless, and filtering was done by a different logic. You can always just chain another filter at the end by adding "| filter:quickSearch" into ng-repeat.