Search code examples
angularjsangularjs-ng-repeatangularjs-filter

How to filter ng-repeat list on empty string values with an inputfield?


How can I filter an ng-repeat to show all items where a certain columnfield is an empty string? When I try this by typing nothing in the field it always seem to give the full list (which is expected). I only want to see the person with id 1. How can I adjust the filter that a certain character in the inputfield makes the ng repeat filter on empty fields for the name column.

FiddleJs Example

My view:

<div class="panel-heading">
   <h3>Filtered by {{filterValue}}</h3>
   <input ng-change="filter()" ng-model="filterValue"/>
</div>
<div class="panel-body">
   <ul class="list-unstyled">
     <li ng-repeat="p in filteredPeople">
       <h4>{{p.name}} ({{p.age}}) id: {{p.id}}</h4>
     </li>
   </ul>
</div>

Controller:

    var people = [{
        name: '',
        age: 32,
        id: 1
    }, {
        name: 'Jonny',
        age: 34,
        id: 2
    }, {
        name: 'Blake',
        age: 28,
        id: 3
    }, {
        name: 'David',
        age: 35,
        id: 4
    }];
    
    $scope.filter = function (value) {
     $scope.filteredPeople = $filter('filter')(people, {
        name: $scope.filterValue
     });
    }

    $scope.people = people.slice(0);

Solution

  • Delete your $scope.filter() function in the controller and the ng-change="filter()" in your view. You should change var people array to $scope.people. You also need to delete the line $scope.people = people.slice(0);.

    Create a filter function in your controller to only return people whose name property is empty if $scope.filterValue is empty:

    $scope.emptyFilter = function(person) {
        if ($scope.filterValue.length === 0) {
            if (person.name.length === 0) {
                return person;
            }
        } else {
            return person;
        }
    };
    

    Next, update your ng-repeat with the following:

    <li ng-repeat="p in people | filter:emptyFilter | filter:{name: filterValue}">