我有一个建议,实现这样的超时:
- $timeout(function() {
- // Loadind done here - Show message for 3 more seconds.
- $timeout(function() {
- $scope.showMessage = false;
- },3000);
- },2000);
- };
有人能告诉我在使用这个而不是使用setTimeout的原因/优势是什么?
在基本词语中$ timeout指的是当setTimeout – 到JavaScript时的angularjs。
如果你仍然想使用setTimeout,你需要调用$ scope。$ apply()
作为旁注
我建议你阅读How do I “think in AngularJS” if I have a jQuery background?帖子
和AngularJS: use $timeout,not setTimeout
示例1:$ timeout
- $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);
演示Fiddle
$ timeout也返回一个promise
JS
- function promiseCtrl($scope,$timeout) {
- $scope.result = $timeout(function({
- return "Ready!";
- },1000);
- }
HTML
- <div ng-controller="promiseCtrl">
- {{result || "Preparing…"}}
- </div>
$ timeout也触发摘要周期
考虑我们有一些3d方代码(不是AngularJS)像Cloudinary插件,上传一些文件,并返回我们的进度的百分比回调。
- // .....
- .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 = file_;
所以空的$ timeout为我们的工作,它将触发摘要周期和$ scope.file更新由3d方将在GUI中重新呈现