Search code examples
angularjsangular-ui-routerrootscope

AngularJS ui-router redirect after log in


I have a project using AngularJS with ui-router. Everything working fine beside the redirect from login screen to preview state on the first load.

Default state is home - http://test/#/

For example, if user is not logged in - http://test/#/test/1000/details goes to login page (which it is supposed to do)

Then after user login, the system goes to default state "home - http://test/#/" but I want to go to http://test/#/requests/1000/details

How do I save the "http://test/#/requests/1000/details or stateName" to redirect after login?

I try using $stateChangeSuccess to save a log of states in the $rootscope but the first one (http://test/#/requests/1000/details) never gets saved.

Any ideas how to handle this?

Thanks.


Solution

  • You can add a 'previous' property to $state in your main-app's run method.

    This is how I solved the problem:

    // add ui-router variables to $rootScope. Comes handy in many cases, for example setting page title
    angular.module('app').run(['$rootScope', '$state', '$stateParams', addUIRouterVars]);
    
    function addUIRouterVars($rootScope, $state, $stateParams) {
        $rootScope.$state = $state;
        $rootScope.$stateParams = $stateParams;
    
        // add previous state property
        $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState) {
            $state.previous = fromState;
        });
    }