AngularJS循环不更新视图
AngularJS loops not updating the view
执行。。循环或While。。循环不会更新$scope变量。我试图显示循环递增时的进度。
我读过(http://jimhoskins.com/2012/12/17/angularjs-and-apply.html)如果没有通过事件或promise(如ng-click()事件或$http调用)检测到更改,我们需要使用$apply来强制更新。
我尝试过使用$apply强制更新,但这似乎没有改变任何事情。
我试过使用$timeout,但测试结果再次为阴性。
在下面的代码中,我尝试了三种不同的测试。最初我尝试了For。。循环,然后我试了一会儿。。循环,然后过一会儿。。循环使用$apply。这些测试是相互独立的,我把这三种测试都包括在内,只是为了向你展示我尝试过的变体。
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
注册超时的循环将始终非常快,并且由于在每次迭代中传递给$timeout
的延迟是相同的,因此它们将同时触发,并且视图将显示为只更新一次。
如果希望视图中的数字逐渐增加,则传递给$timeout
的延迟需要增加,如下面的示例所示。此外,由于i
的值在每次迭代中都会永久更改,因此请确保根据其当前值递增progress
变量。
for (i = 0; i <= $scope.counterMax; i++) {
$timeout(function() {
$scope.progress++;
}, i);
}
相关文章:
- $routeParams在传递到新视图时未定义&控制器
- 从 AngularJS 中的 ngview 内部的视图更新主页
- 如何在渲染新视图之前关闭所有事件
- 从Backbone中的另一个视图调用新视图
- 如何在一个时间间隔后追加新的更新
- Angular2 在创建 ngSwitch 新视图后调用自定义函数
- angularJS视图更新后初始化引导工具提示
- 使用新项目更新KendoUI网格数据源
- 使用新值更新时出现数组问题
- 定期轮询数据库,Rails 视图更新而不刷新
- 如何在 AngularJs 中的数据库发生变化时立即实现自动视图更新
- 使用Plotly中的新数据更新图形的高性能方法
- MySQL 按行[id]使用新信息更新“n”行数
- 使用新数据更新 D3 饼图.json
- 主干新视图反映旧模型数据
- 对数据库进行 AJAX 编辑时,我是否应该立即使用新数据更新接口
- 如何从 AngularJS 视图更新变量
- ngModel 不会在第一次触发视图更新
- 创建新视图时调用呈现函数
- 使用从 MongoDB 获取的新数据更新对象属性