【发布时间】:2015-11-19 12:41:02
【问题描述】:
执行 For..Loops 或 While..Loops 不会更新 $scope 变量。我试图在循环增加时显示进度。
我已阅读 (http://jimhoskins.com/2012/12/17/angularjs-and-apply.html) 如果未通过事件或承诺(如 ng-click() 事件或 $http 调用)检测到更改,我们需要使用 $apply 强制更新。
我尝试使用 $apply 强制更新,但这似乎并没有改变任何东西。
我曾尝试使用 $timeout,但测试结果再次为阴性。
在下面的代码中,我尝试了三种不同的测试。最初我尝试了一个 For..loop,然后我尝试了一个 while..loop,然后我尝试了一个带有 $apply 的 while..loop。这些测试相互独立,我将所有三个测试都包括在内只是为了向您展示我尝试过的变体。
var myApp = angular.module('myApp', []);
myApp.controller('CounterController', ['$scope', '$timeout', function($scope, $timeout) {
$scope.counterMax = 5000;
$scope.startCounter = function() {
$scope.progress = 0;
$scope.progress2 = 0;
$scope.progress3 = 0;
// for loop $scope test
for (i = 0; i <= $scope.counterMax; i++) {
$timeout(function() {
$scope.progress = i;
}, 500);
}
// while loop $scope test
var x = 0;
try {
while (x < $scope.counterMax) {
$timeout(function() {
$scope.progress2 = x;
}, 2);
x++;
}
} catch (error) {
console.log("Error: " + error);
}
// while loop $scope test with $apply
x = 0;
try {
while (x < $scope.counterMax) {
$timeout(function() {
$scope.$apply(function() {
$scope.progress3 = x;
});
}, 2000);
x++;
}
} catch (error) {
console.log("Error: " + error);
}
}
$scope.startCounter();
}]);
景色
<div ng-controller="CounterController">
<p>
Depending on the value for the Counter Max, a loop will be made from zero to
the Counter Max value.
<br />
The value in the Progress Indicators should increment gradually until the Counter Max value is reached.
<br />
Currently this is not happening. The Progress Indicators are only updated at the
end of the loop.
</p>
<p>
Counter Max: <input type="text" ng-model="counterMax" ng-keyup="startCounter()"/>
</p>
<p>(for loop $scope test)<br />
Progress Indicator 1: {{progress}}</p>
<p>(while loop $scope test)<br />
Progress Indicator 2: {{progress2}}</p>
<p>(while loop $scope test with $apply)<br />
Progress Indicator 3: {{progress3}}</p>
</div>
您可以在 plnkr 上查看我在此处所做的测试: http://plnkr.co/edit/Nl3GMy0DJNJ53PFObAq1?p=preview
【问题讨论】:
标签: javascript angularjs loops angularjs-scope