Search code examples
javascriptangularjsangularjs-ng-repeatangular-filters

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


How can I filter an ng-repeat to show all items where a certain columnfield is an empty string? When I try this it always seem to give the full list. I only want to see the person with id 1.

Fiddlejs example

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.filteredPeople = $filter('filter')(people, {
     name: ''
 });

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

View:

<li ng-repeat="p in filteredPeople">
     <h4>{{p.name}} ({{p.age}}) id: {{p.id}}</h4>
</li>

Solution

  • You can use Angular's 'filter' in 'ng-repeat':

    // In template:
    <li ng-repeat="p in filteredPeople | filter : filterPeople">
         <h4>{{p.name}} ({{p.age}}) id: {{p.id}}</h4>
    </li>
    
    // In controller:
    $scope.filterPeople = function(item) {
        return !item.name;
    };