angularjs – 在Angular JS中使用$timeout而不是window.setTimeout有什么优点?

前端之家收集整理的这篇文章主要介绍了angularjs – 在Angular JS中使用$timeout而不是window.setTimeout有什么优点?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个建议,实现这样的超时:
  1. $timeout(function() {
  2.  
  3. // Loadind done here - Show message for 3 more seconds.
  4. $timeout(function() {
  5. $scope.showMessage = false;
  6. },3000);
  7.  
  8. },2000);
  9. };

有人能告诉我在使用这个而不是使用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

  1. $scope.timeInMs = 0;
  2.  
  3. var countUp = function() {
  4. $scope.timeInMs+= 500;
  5. $timeout(countUp,500);
  6. }
  7. $timeout(countUp,500);

示例2:setTimeout(相同的逻辑)

  1. $scope.timeInMs_old = 0;
  2.  
  3. var countUp_old = function() {
  4. $scope.timeInMs_old+= 500;
  5. setTimeout(function () {
  6. $scope.$apply(countUp_old);
  7. },500);
  8. }
  9.  
  10. setTimeout(function () {
  11. $scope.$apply(countUp_old);
  12. },500);

演示Fiddle

$ timeout也返回一个promise

JS

  1. function promiseCtrl($scope,$timeout) {
  2. $scope.result = $timeout(function({
  3. return "Ready!";
  4. },1000);
  5. }

HTML

  1. <div ng-controller="promiseCtrl">
  2. {{result || "Preparing…"}}
  3. </div>

$ timeout也触发摘要周期

考虑我们有一些3d方代码(不是AngularJS)像Cloudinary插件上传一些文件,并返回我们的进度的百分比回调。

  1. // .....
  2. .on("cloudinaryprogress",function (e,data) {
  3. var name = data.files[0].name;
  4. var file_ = $scope.file || {};
  5. file_.progress = Math.round((data.loaded * 100.0) / data.total);
  6.  
  7.  
  8. $timeout(function(){
  9. $scope.file = file_;
  10. },0);
  11. })

我们想更新我们的用户界面$ scope.file = file_;

所以空的$ timeout为我们的工作,它将触发摘要周期和$ scope.file更新由3d方将在GUI中重新呈现

猜你在找的Angularjs相关文章