UI-Router state.go call back on state change

All we need is an easy explanation of the problem, so here it is.

I need a callback when state.go has been invoked successfully, and set my alert message.
Currently the message is pushed to the array, after state.go has been called.
State.go calls the controller, and the array containing the alert message is set to empty.

Result, no alert message will be shown.

Controller:

$scope.alerts = []; // empty array, initialized on startup
.....
// This could be any function
.success(function(data, status, headers, config, statusText){
     $state.go($state.current, {}, {reload : true});
     $scope.alerts.push({type : 'success', msg : status});
})
.error(function(error){
    console.log(error.message);
});

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

$state.go() returns a promise.

So do something like:

$state.go('wherever', {whenever: 'whatever'}).then(function() {
  // Get in a spaceship and fly to Jupiter, or whatever your callback does.
});

Method 2

You may use state change listener.

 $rootScope
            .$on('$stateChangeSuccess',
                function (event, toState, toParams, fromState, fromParams) {
                    //show alert()
                });

See State Change Events.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply