Search code examples
angularjsangular-ui-routerstateangularjs-rootscope

Use UI-router to navigate to fromState


AngularJS UI-router has a useful parameter "fromState" which allows me to store where the user came from when they change state. I am trying to implement a system which takes the user back where they left off if they are taken to a subscribe / login / signup state. I capture the fromState, they perform the action, then if my fromState var is set the user will be taken back to that state. But it doesn't work! Example:

.run(function ($rootScope, $state, $timeout, $location, $anchorScroll) {
  $rootScope.$on('$locationChangeSuccess', function (event, toState, fromState) {
    $rootScope.loggedFromState = fromState;
    console.log($rootScope.loggedFromState);

Outputs "http://my-app-url/page-name"

I would then like to do something like this :

$state.go($rootScope.loggedFromState);

But that doesn't work. A state has to be a state name + params, but fromState is in a URL format. How do I navigate to $rootScope.loggedFromState ("http://my-app-url/page-name")?


Solution

  • A more appropriate way is to use ui-router hooks : https://ui-router.github.io/guide/transitionhooks

    $transitions.onStart({}, function(transition) {
        console.log(
        "Transition from " + transition.from().name +
        " to " + transition.to().name
        );
    
        let from = transition.from().name;
        // validation
        // if validation fails abort transition
        transition.abort();
        // and redirect somewhere else
        $state.go(from);
    
    });
    

    Then you can take the state name:

    let from = transition.from().name;
    

    first abort current transition:

    transition.abort();
    

    and then redirect:

    $state.go(from);