Angular - ui-router get previous state
ui-router doesn't track the previous state once it transitions, but the event $stateChangeSuccess
is broadcast on the $rootScope
when the state changes.
You should be able to catch the prior state from that event (from
is the state you're leaving):
$rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
//assign the "from" parameter to something
});
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;
}]
}
});
}]);