下面是一个使用 angularjs 构建的非常简单的 TODO 应用程序。
到目前为止它工作正常,但我的问题是 angularjs 一直在输入字段中的每次击键时调用“剩余”函数!!下面的代码有什么问题吗?
<!doctype html>
<html ng-app>
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
<link href="style.css" rel="stylesheet">
</head>
<body>
<div>
<h2>TODO:</h2>
<div ng-controller="TodoCtrl">
<span>{{remaining()}} of {{todos.length}} remaining</span> [ <a href="" ng-click="archive()">archive</a> ]
<ul class="list-unstyled">
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done" >
<span>{{todo.text}}</span>
</li>
</ul>
<form ng-submit="addTodo()">
<input type="text" ng-model="todo" placeholder="Enter your task here">
<form>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<!--script src="app.js"></script-->
<script>
function TodoCtrl($scope) {
$scope.todos = [
{text: 'learn angular', done:true},
{text: 'build an angular app', done:false}
];
$scope.remaining = function() {
console.log('calling remaining()');
var count = 0;
angular.forEach($scope.todos, function(todo) {
count += todo.done? 0:1;
});
return count;
};
$scope.addTodo = function() {
if($scope.todo) {
$scope.todos.push({text: $scope.todo, done:false});
}
$scope.todo = '';
};
}
</script>
</body>
</html>
最佳答案
这是标准的 Angular 行为。在对模型或任何其他绑定(bind)或 Angular 事件进行任何更改时,它将执行在示波器上设置的所有监视。这称为摘要循环,通常由 $scope.$apply() 触发。这就是为什么不要对从 View 中的绑定(bind)表达式调用的函数进行任何繁重的计算是极其重要的。
性能问题通常发生在函数对长列表进行计算或过滤时。如果这是一个问题,解决方案是在集合上设置一个监视,并仅在集合发生变化时将计算属性更新为作用域中的单独变量。在您的示例中,这将防止在不相关的输入发生变化的情况下重新计算剩余的项目。
关于javascript - 为什么 angularjs 在每次输入更改时都不必要地继续调用 Controller 函数以及如何停止该行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20951188/