什么好处是在有使用角JS,而不是window.setTimeout的$超时? [英] What advantage is there in using the $timeout in Angular JS instead of window.setTimeout?
问题描述
我有一个建议,以实现这样的超时:
I had a suggestion to implement a timeout like this:
$timeout(function() {
// Loadind done here - Show message for 3 more seconds.
$timeout(function() {
$scope.showMessage = false;
}, 3000);
}, 2000);
};
有人能告诉我什么是使用这个,而不是使用setTimeout的原因/优势?
Can someone tell me what is the reason / advantage in using this rather than using setTimeout?
推荐答案
在基本词汇 $超时
指angularjs当的setTimeout
- 为JavaScript
In basic words $timeout
refers to angularjs when setTimeout
- to JavaScript.
如果你仍然认为使用的setTimeout
因此,您需要调用 $范围。$适用()
在
If you still think to use setTimeout
therefore you need invoke $scope.$apply()
after
的作为一个方面说明的
我建议你读<大骨节病> How我认为AngularJS如果我有一个jQuery的背景是什么? 骨节病>发表
I suggest you to read How do I "think in AngularJS" if I have a jQuery background? post
和<大骨节病> AngularJS:使用$超时,而不是setTimeout的 骨节病>
$scope.timeInMs = 0;
var countUp = function() {
$scope.timeInMs+= 500;
$timeout(countUp, 500);
}
$timeout(countUp, 500);
例2:的setTimeout(相同的逻辑)
$scope.timeInMs_old = 0;
var countUp_old = function() {
$scope.timeInMs_old+= 500;
setTimeout(function () {
$scope.$apply(countUp_old);
}, 500);
}
setTimeout(function () {
$scope.$apply(countUp_old);
}, 500);
演示<大骨节病> 小提琴 骨节病>
的 JS 的
function promiseCtrl($scope, $timeout) {
$scope.result = $timeout(function({
return "Ready!";
}, 1000);
}
的 HTML 的
<div ng-controller="promiseCtrl">
{{result || "Preparing…"}}
</div>
$超时也引发消化周期
考虑,我们有一些3D方code(不AngularJS)像Cloudinary插件,上传一些文件,并返回美国的进步百分比率回调。
$timeout also trigger digest cycle
Consider we have some 3d party code (not AngularJS) like Cloudinary plugin that uploads some file and returns us 'progress' percentage rate callback.
// .....
.on("cloudinaryprogress",
function (e, data) {
var name = data.files[0].name;
var file_ = $scope.file || {};
file_.progress = Math.round((data.loaded * 100.0) / data.total);
$timeout(function(){
$scope.file = file_;
}, 0);
})
我们要更新我们又名 $ scope.file =文件UI _;
所以的空的 $超时
为我们做这项工作,它会引发消化周期和 $ scope.file
三维方更新将重新呈现在GUI
So empty $timeout
does the job for us, it will trigger digest cycle and $scope.file
updated by 3d party will be re-rendered in GUI
这篇关于什么好处是在有使用角JS,而不是window.setTimeout的$超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!