gpt4 book ai didi

javascript - 如何限制在angularjs中调用模型函数的频率?

转载 作者:行者123 更新时间:2023-11-30 17:54:07 26 4
gpt4 key购买 nike

我只是在学习angularjs并拆开第一个示例,一个连接到待办事项 javascript 模型的待办事项列表。

在 html 中我们有:

<div ng-controller="TodoCtrl">
<span>{{remaining()}} of {{todos.length}} remaining</span>

在 Controller 脚本中我们有:

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

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

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

最佳答案

您可以在作用域上使用 $watch 方法在待办事项更改时使用react。我不能说这种方式对性能是否更好。

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

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

关于javascript - 如何限制在angularjs中调用模型函数的频率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18417922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com