Search code examples
javascriptangularjsangularjs-routing

Angular JS UI Routing


I am trying to use angularJS UI routing. I have three webpages, clients can access the first page through some link but if the url has a token attached to it I am doing a $state.go('second-page') in the controller. If the token is null I keep the client on the first page. However I want that when the client presses the back button on the browser the client should go to the first page. Which does not happen.

So the scenario is

client comes through the link

'#/form/calendar/:officeId/:token'

and since the token is not null I transition to the second page which does not have a URL the URL now becomes

'#/form/'

but when the client presses the back button it tries to go to

'#/form/calendar/:officeId/:token'

which results in a cyclic transition to the second page and the client can never reach the first page.

Please advise on how to avoid this.

Thank You


Solution

  • There's nothing in the router that's really designed for this, but it's fairly easy to implement yourself. The router posts a $stateChangeStart event that you can listen to. On the second trigger you would simply want to inhibit this redirect. Or simply DO the redirect in there, one time:

    var redirected = false;
    $rootScope.$on('$stateChangeStart', function(e, to, toParams, from, fromParams) {
        // Redirect the user but only once
        if (!redirected && toState.whateverYouWantToCheck) {
            e.preventDefault();
            redirected = true;
            $state.go(...);
        }
    });
    

    This will allow you to perform the redirect but only one time.