2013-03-24 65 views
2

使用AngularJS ng-repeat,我正在過濾一個人員列表。生成的人員列表被傳遞給變量filtered。我想顯示filtered.length當ng-repeat過濾器更新時AngularJS過濾結果不會更新

過濾器正常工作並在調整過濾器時顯示正確的人員,但有多少人(即filtered.length)有時不會更新。

這似乎很奇怪:

<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> 

但似乎如果我展示filtered.length在頁面的底部,ng-repeat後,它的工作原理。如果我把它放在最上面,它只能在80%的時間內工作。

回答

1

能移動過濾方法給控制器,以便可以更新一個長度可變:

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

0

我發現不幸的是需要運行過濾多次的解決方案:

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

它會好起來的我的小數據集,但讓我知道如果你可以看到在我原來的問題的bug。

+0

嘗試移動所述過濾器到控制器作爲一個功能,並且可以更新與所得陣列的長度的範圍可變 – charlietfl 2013-03-24 16:34:13