1

I wanted to know if there is a way in Angular to refresh a single page application and properly go back to the same state as before? I am using ui-router (version 0.2.15) for defining different states.

Currently, I am storing the state name using ngStorage and have placed $state.go(last_stored_state_name) in the controller of the state that loads first. This way I get to the state that i was on before refresh but the problem is i can see the first state's view just for a second before $state.go(last_stored_state_name) runs.

Can anyone please tell me how I can bypass the first state's view directly to the desired state?

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
user2470087
  • 49
  • 13

2 Answers2

0

Try this:

$state.go($state.current, {}, {reload: true});
lahsrah
  • 9,013
  • 5
  • 37
  • 67
0

Create a controller and add it with ng-controller at any top level element like on <body> tag so that its scope is available throughout the application and in that controller, do like this:

// Event listener for state change.
$scope.$on('$stateChangeStart', function(event, toState, toParams, fromState) {
    if (last_stored_state_name && isPageRefresh) {
        // prevent execution of current state and navigate to last saved state
        event.preventDefault();
        $state.go(last_stored_state_name);
        return;
    }
});

So you don't have to do $state.go(last_stored_state_name); in your controller. This way, you will not see the first state for a second.

You can figure out a variable isPageRefresh with any type of checks like checking if fromState is null or setting a local storage variable or setting a global javascript variable .

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
  • I have actually done something similar to this. I have captured the refresh event using windowElement.on('beforeunload', function (event) {}) and have set the storage variables inside it. This i have done in every controller so that refresh from anyone will trigger the saving of state. The problem lies after this when the view loads. – user2470087 Apr 17 '16 at 08:10
  • I tried your answer. I detected the refresh event in the state using my earlier approach and added your approach in a top level controller to change the state after reload. It still is not working. Moreover, the $state.go() in your approach is not getting executed. – user2470087 Apr 17 '16 at 12:42