您可以採取多種方法,但都是先緩存控制器加載時完成的項目數。
您可以使用$watch
函數來監視數組,並在對象更改時更新計數器。以下是未經測試,但應該給你怎麼辦呢
function myCtl($scope, itemFetcher) {
$scope.items = itemFetcher.get(); //retrieves your array of items
$scope.numComplete = countComplete();
$scope.$watch("items", function(newValue, oldValue) {
$scope.items = newValue;
$scope.numComplete = countComplete();
}, true); // NOTE: passing true into $watch is necessary to do a deep compare (i.e. comparing object properties), and I think it is required in this case, but it has a negative impact on performance & memory.
function countComplete() {
var cnt = 0;
angular.forEach($scope.items, function(item) {
cnt += item.completed ? 1 : 0;
}
return cnt;
}
}
或者,您可以更新在修改完成狀態的項目功能完成計數感。以下代碼也未經測試。
function myCtl($scope, itemFetcher) {
$scope.items = itemFetcher.get(); //retrieves your array of items
$scope.numComplete = countComplete();
$scope.markItem = function(index, newState) { // this function is referenced in your HTML template
$scope.items[index].complete = newState;
$scope.numComplete += (newState) ? 1 : -1;
}
function countComplete() {
var cnt = 0;
angular.forEach($scope.items, function(item) {
cnt += item.completed ? 1 : 0;
}
return cnt;
}
}
使用$watch
更方便和更不易出錯,但可能會導致依賴於items
陣列的大小的性能問題。第二種方法更高效,但更難維護。
想法不錯,但我敢打賭,過濾方法與使用$ watch的大型數組項目具有相同的性能影響。這一切都取決於如何實現過濾器,我的猜測是它依賴於angular.equals這是一個潛在的性能殺手。 – Jason 2014-09-23 13:18:49