我只是在学习angularjs并挑选第一个例子,一个连接到todo javascript模型的待办事项列表。
在html中我们有:
<div ng-controller="TodoCtrl">
<span>{{remaining()}} of {{todos.length}} remaining</span>
在控制器脚本中,我们有:
$scope.remaining = function () {
// --> THIS ALERT IS CALLED ON EACH KEYSTROKE
alert('remaining called');
var count = 0;
angular.forEach($scope.todos, function (todo) {
count += todo.done ? 0 : 1;
});
return count;
};
我认为如果在每次击键时都会出现延迟问题,则必须对所有对控制器的引用进行评估。
可以使用哪种方法来提高效率?
答案 0 :(得分:2)
您可以使用范围内的$ watch方法在待办事项更改时作出反应。 我不能说这种表现更好。
$scope.$watch('todos', function() {
$scope.remaining = ... // remaining just int
}, true);
此外,如果您使用新的角度,请查看$watchCollection方法。