Search code examples
angularjsangular-ui-routerback

How to move to a particular state on click of browser back without affecting ui-router state machine


I am creating a secured website (using AngularJS 1.3) where I want to redirect the user to 'Login' state if he clicks browser back button. I am using ui-router for state changes, and I make use stateChangeSuccess event and previousState property for other use cases. So, clearing out window history may not be an option if it clears out ui-router's previousState information also.

Thanks


Solution

  • I had the same problem and i made a workaround like this:

    You can use ui-router optional parameters:

    https://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$stateProvider

    An example:

    $stateProvider.state('yourState', {
            url: "/url",
            templateUrl: 'yourTemplate',
            params: {
                click: {value: "false"}
            }
        }
    )
    

    In the ui-sref (my button), i use:

    ui-sref="yourState({click: 'true'})"
    

    After that you can use the $stateChangeStart to prevent go back or do whatever you want:

    $rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
        if (toState.name === 'yourState') {
            if (toParams.click == 'false') {
                // DO YOUR THING
            }
        };
    });
    

    I know that is not a generic solution, but i think that you can adapt this to work with all your application (maybe regular expresions for the state name)