Rusty Rob
Rusty Rob

Reputation: 17203

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.

Upvotes: 2

Views: 8526

Answers (2)

charlietfl
charlietfl

Reputation: 171690

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

Upvotes: 1

Rusty Rob
Rusty Rob

Reputation: 17203

I've found a solution which unfortunately requires running the filter multiple times:

    People Selected: {{(data.people | filter:okay).length}}<br><br>
    Cost: {{(data.people | filter:okay).length*0.02|currency}}

It will be okay for my small data set but let me know if you can see the bug in my original question.

Upvotes: 0

Related Questions