javascriptangularangular-ui-routerangular-promiseangular-transitions

How to prevent state transition, when there is another transition running in angular ui router?


In my angular app, I have this issue. When user quickly double-clicks link to state (ui-sref link), the target state begins loading twice. This would be bearable, if the state window didn't freeze and stop responding to other state changes. When clicking another ui-sref links, URL changes accordingly, http calls on background are made, but the view is frozen.

I need to know, how can I prevent any transition, when there is another transition already trying to resolve promise. I know I can somehow work magic with $stateChangeStart and event.preventDefault(). What I don't know is how to allow my transition to continue after resolving it's resolve block and how to counterpart event.preventDefault().

Thanks for your time. Any advice will be greatly appreciated.


Solution

  • Angular UI Router's $state object has a property on it, 'transition', which will be present if it is in the middle of an active transition. One option is to remove the ui-sref attribute and use a ng-click attribute instead. Inside your ng-click function, you can do a manual check for the presence of the transition object before invoking $state.go().

    Before

    HTML:

    <a ui-sref="Root.State1">
    

    After

    HTML:

    <a href="" ng-click="goToStateOne()">
    

    JS:

    scope.goToStateOne = function() {
      if (!$state.transition) $state.go('Root.State1');
    }