Tim Fountain Tim Fountain - 1 month ago 14
AngularJS Question

Ignoring blank dropdown values in an AngularJS filter

I have a tabular list of user data which I'm adding 'advanced search' functionality to. The advanced search consists of a number of dropdowns allowing users to filter their results, for example, limiting the results to users from a particular department:

<select ng-model="search.department_id" ng-options="department.id as department.name for department in departments">
<option value="">(Select from list)</option>
</select>


The results are then displayed using:

<table>
<tr ng-repeat="user in users | filter:search | orderBy:'name')">
<td> [code to show user data here.] </td>
</tr>
</table>


If you select a department from the dropdown, this works correctly. But if you change your mind and pick the default '(Select from list)' option again, only users with a blank department_id value are shown. What I want to happen is for the department dropdown to be ignored if no department is selected.

After some searching around, it looked like I could solve this using a custom comparator, so I wrote this:

$scope.ignoreNullComparator = function(expected, actual){
if (expected === null) {
return true;
} else {
return angular.equals(expected, actual);
}
};


and changed the
ng-repeat
to:

ng-repeat="user in users | filter:search:ignoreNullComparator | orderBy:'name'


but although with some debugging could see the custom comparator being used, it didn't make any difference to the results.

So, how can I get the filter to ignore the dropdowns if the blank option is selected?

Answer

The order of parameters in your comparator is wrong, comparator should be defined as function(actual, expected):

$scope.ignoreNullComparator = function(actual, expected){
    if (expected === null) {
        return true;
    } else {
        return angular.equals(expected, actual);
    }
};