您可以采取多种方法,但都是先缓存控制器加载时完成的项目数。
您可以使用$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