Search code examples
angularjsangularjs-ng-repeatangular-filters

AngularJS filtered result not updating when filter updates from ng-repeat


With AngularJS ng-repeat, I'm filtering a list of people. The list of resulting people is passed to a variable filtered. I want to display filtered.length.

The filter works correctly and displays the right people when I adjust the filters, however the count of how many people (i.e. filtered.length) sometimes doesn't update.

It seems rather strange:

    <br><br>
    People Selected: {{filtered.length}}<br><br>
    Cost: {{filtered.length*0.01 | currency}}
</div>
<div class="span10">
    <br><br>
    <table class="people">
        <tr ng-repeat="person in (filtered = (data.people | filter:okay))">
            <td>{{person.age}} - {{person.gender}} - {{person.tags}}</td>
        </tr>
    </table>
</div>

However it seems if I show the filtered.length at the bottom of the page, after the ng-repeat, it works. If I put it at the top it only works 80% of the time.


Solution

  • Could move filter method to controller so you can update a length variable:

    app.controller('MainCtrl', function($scope) {
    
      var items=[
        {name:'Jim', ok: true},
        {name:'Sue', ok: true},
        {name:'Bob', ok: false},
    
        ];
    
        $scope.$watch('filter.value',function(){     
          $scope.items=items.filter(function(item){
             return item[$scope.filter.property]==$scope.filter.value
          })
          $scope.num_items=$scope.items.length;
    
        });
        $scope.filter={value:true, property: 'ok'}
    });
    

    Plunker demo