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.

PTD
  • 1,028
  • 1
  • 16
  • 23
Valter
  • 2,859
  • 5
  • 30
  • 51

1 Answers1

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;
    });
}
Joe Samanek
  • 1,644
  • 12
  • 16
  • 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="http://test/#/request/1000/details, etc...}, Correct? – Valter Dec 10 '14 at 16:22
  • 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). – Joe Samanek Dec 10 '14 at 17:07
  • If you want to read more about this, try this thread: https://github.com/angular-ui/ui-router/issues/92 – Joe Samanek Dec 10 '14 at 17:10
  • Hi Joe, after closer look... there was code that redirect to the homepage after login every time. This works now. Thanks. – Valter Dec 11 '14 at 14:20