3

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.

1

1 Answer 1

7

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;
    });
}
Sign up to request clarification or add additional context in comments.

4 Comments

I added this but it is saving {url="^", abstract=true, name="", views=null, transition=null}, it is not saving the right data, it should be {url="test/#/request/1000/details, etc...}, Correct?
It works for me. It can look like this for example: Object {url: "/posts", templateUrl: "../AngularApp/post/posts.html", data: Object, resolve: Object, controller: "postsCtrl as vm"…} Your values are the defaults values I think, which will be there if there is no previous state yet (ie. you started your app with that state).
If you want to read more about this, try this thread: github.com/angular-ui/ui-router/issues/92
Hi Joe, after closer look... there was code that redirect to the homepage after login every time. This works now. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.