Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - ui-router get previous state

Is there a way to get the previous state of the current state?

For example I would like to know what the previous state was before current state B (where previous state would have been state A).

I am not able to find it in ui-router github doc pages.

like image 473
Mihai H Avatar asked Oct 17 '22 06:10

Mihai H


People also ask

How to go previous state in AngularJS?

var previous = $previousState. get(); //Gets a reference to the previous state. previous is an object that looks like: { state: fromState, params: fromParams } where fromState is the previous state and fromParams is the previous state parameters.


1 Answers

I use resolve to save the current state data before moving to the new state:

angular.module('MyModule')
.config(['$stateProvider', function ($stateProvider) {
    $stateProvider
        .state('mystate', {
            templateUrl: 'mytemplate.html',
            controller: ["PreviousState", function (PreviousState) {
                if (PreviousState.Name == "mystate") {
                    // ...
                }
            }],
            resolve: {
                PreviousState: ["$state", function ($state) {
                    var currentStateData = {
                        Name: $state.current.name,
                        Params: angular.copy($state.params),
                        URL: $state.href($state.current.name, $state.params)
                    };
                    return currentStateData;
                }]
            }
        });
}]);
like image 153
Endy Tjahjono Avatar answered Oct 18 '22 19:10

Endy Tjahjono