简体   繁体   English

没有$ timeout,UI Route加载微调器将无法工作

[英]UI Route loading spinner doesn't work without $timeout

I have an angular app using UI Router. 我有一个使用UI Router的角度应用程序。 I have subscribed to the $stateChangeStart and $stateChangeSuccess events and I'm using an ng-show directive to show/hide a controller property for "isLoading" for a loading indicator outside of the ui-view tag. 我已经订阅了$ stateChangeStart和$ stateChangeSuccess事件,并且正在使用ng-show指令为ui-view标记之外的加载指示器显示/隐藏“ isLoading”的控制器属性。 I can debug through the code and see that the events are firing and the variables are being set in JS, but it seems that between the start and success events, the DOM is never updated and so my loading indicator never shows. 我可以调试代码,看到事件正在触发,并且变量已在JS中设置,但是似乎在启动事件和成功事件之间,DOM从未更新,因此我的加载指示器从未显示。 The only way I could get the loading indicator to show up is to add a $timeout of 0 seconds and do the variable update there. 我可以使加载指示器显示的唯一方法是添加0秒的$ timeout并在那里进行变量更新。

$rootScope.$on("$stateChangeStart", function() {
    ctrl.isLoading = true;
});
$rootScope.$on("$stateChangeSuccess", function(ev, to, toParams, from, fromParams) {
    $timeout(function() {
      ctrl.isLoading = false;
    }, 0);
});

This JSFiddle http://jsfiddle.net/uwhetx7q/2/ demonstrates what I am struggling with. 这个JSFiddle http://jsfiddle.net/uwhetx7q/2/展示了我正在努力解决的问题。

When the $timeout is being applied, even at 0 seconds, the loading indicator flashes. 当应用$ timeout时,即使在0秒时,加载指示灯也会闪烁。 But without it, my variable is never $apply'd. 但是没有它,我的变量将永远不会被应用。

I tried actually calling $apply and $digest, but I get the error that those methods are already in progress. 我试过实际上调用$ apply和$ digest,但是我得到了那些方法已经在执行中的错误。

I am hoping there is something super obvious that I am missing that would get my loading indicator to show because an empty $timeout is a bad solution :) 我希望有一些我很想念的东西,因为空的$ timeout是一个不好的解决方案,所以我的加载指示器会显示出来:)

Thanks! 谢谢!

You have a scope/digest-timing problem. 您有范围/摘要时间问题。 Your ctrl.isLoading will be set, but the thing (the spinner I guess) does not recognize this immediatly. 您的ctrl.isLoading将被设置,但是该东西(我猜是微调器)无法立即识别出这一点。 After the current digest cycle, your variable will be updated. 在当前摘要周期之后,您的变量将被更新。

Do this (it's common and valid): 执行此操作(这是常见且有效的):

$rootScope.$on("$stateChangeSuccess", function(ev, to, toParams, from, fromParams) {
    $timeout(function() {
      ctrl.isLoading = false;
    });
});

$timeout without any time will run after the current digest-cycle has been finished. 当前摘要周期完成后,将立即运行$ timeout,而不会花费任何时间。

More information about scope/digest/apply: http://www.codingeek.com/angularjs/angular-js-apply-timeout-digest-evalasync/ 有关scope / digest / apply的更多信息: http : //www.codingeek.com/angularjs/angular-js-apply-timeout-digest-evalasync/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM