Angular - ui-router get previous state

Mihai H picture Mihai H · May 19, 2013 · Viewed 152.5k times · Source

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.

Answer

Endy Tjahjono picture Endy Tjahjono · Sep 20, 2014

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: $state.params,
                        URL: $state.href($state.current.name, $state.params)
                    };
                    return currentStateData;
                }]
            }
        });
}]);