【发布时间】:2013-11-17 14:11:21
【问题描述】:
我是 AngularJS 的新手。我正在考虑使用$timeout 服务。我已经读到,在 JavaScript setTimeout 函数上使用 $timeout 的原因之一是因为在调用 $scope.$apply 之前,对 $scope 中变量的更改不会在 UI 中更新。虽然就是这个词,但我无法用实际代码确认这一点。我写了以下内容:
index.html
<div ng-app="myApp">
<div ng-controller="myController">
<div>AngularJS Count: {{total1}}</div>
<br />
<div>setTimeout Count: {{total2}}</div>
<br />
<button ng-click="start()">start</button>
</div>
</div>
myController.js
var app = angular.module("myApp", []);
function myController($scope, $timeout) {
$scope.total1 = 0;
$scope.total2 = 0;
$scope.isStarted = false;
$scope.toggle = function() {
if (!$scope.isStarted) {
$scope.isStarted = true;
$timeout(ngUpdate, 1000);
setTimeout(jsUpdate, 1000);
}
};
function ngUpdate() {
$scope.total1 = $scope.total1 + 1;
}
function jsUpdate() {
$scope.total2 = $scope.total2 + 1;
}
}
在此代码示例中,对 $scope 上的变量所做的更改会在 UI 中更新。我试图在代码中看到一个场景,其中通过 setTimeout 函数进行的更改在调用 $scope.$apply 之前不会更新 UI。我是不是误会了?或者是对 AngularJS 框架进行了更改,导致原始断言过时。
【问题讨论】:
-
对不起,我的例子错了。我将对其进行更多研究并再次回答:)
标签: angularjs settimeout angularjs-timeout