简体   繁体   中英

UI Route loading spinner doesn't work without $timeout

I have an angular app using 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. 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. 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.

$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.

When the $timeout is being applied, even at 0 seconds, the loading indicator flashes. 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.

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 :)

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. 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.

More information about scope/digest/apply: http://www.codingeek.com/angularjs/angular-js-apply-timeout-digest-evalasync/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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