Ignoring dropdown values ​​in AngularJS filters

I have a tabular list of user data to which I add the "advanced search" functionality. Advanced search consists of several drop-down menus that allow users to filter their results, for example, restricting results to users from a specific 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>

Then the results are 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 drop-down list, this will work correctly. But if you change your mind and select the default option again ("Choose from the list"), only users with an empty department_id value will be shown. I want the dropdown menu to be ignored if no department is selected.

, , :

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

ng-repeat :

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

, .

, , ?

+4
2

, function(actual, expected):

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

$scope.ignoreNullComparator = function(actual, expected){            
            if (expected === null || expected === '' || typeof expected === "undefined") {
                return true;
            } else   if(!isNaN(expected)) {
                expected2 = parseInt(expected);
                return angular.equals(expected2, actual);
            } else  if( actual.indexOf(expected) === -1 ){
                return false;
            }
            return true;        
        };
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Hide result
0

Source: https://habr.com/ru/post/1544772/


All Articles