如何限制angularjs中对模型函数的调用频率

How to limit frequency of calls to model functions in angularjs?

本文关键字:函数 调用 频率 模型 何限制 angularjs      更新时间:2023-09-26

我只是在学习angularjs,并拆开第一个例子,一个连接到todojavascript模型的todo列表。

在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;
};

我认为,如果每次按键都必须评估对控制器的所有引用,这可能会成为一个延迟问题。

如果有的话,可以使用什么方法来提高效率?

您可以在scope上使用$watch方法来在todos更改时做出反应。我不能说这样做对表现更好。

$scope.$watch('todos', function() {
    $scope.remaining = ... // remaining just int
}, true);

此外,如果您使用新的angular,请查看$watchCollection方法。