How do I know which State I’m coming from using ui-router?

Asked

Viewed 304 times

1

I’m using Angular-Ui ui ui and the only thing I need to know is which state I’m coming from. I already have for example;

app.controller("MainCtrl", function($scope,$state) {
    //$state.current ok, mas de onde eu vim?    
});

How to know which previous state called the current?

1 answer

2


This feature was suggested in the ui-router repository (Github Issue (in English)) and seems to have a feedback positive, but for now there is still no simplified way to get this information.

A possible workaround pointed out in the comments of Issue previously mentioned is to listen to the event $stateChangeSuccess in $rootScope, whose callback receives the object of $state as an argument, thus being able to save it in the $rootScope. Thus, the data from the $state are accessible in all scopes inherited from the $rootScope. Plunker:

app.run(function ($rootScope) {
  $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
    $rootScope.previousState = fromState;
  });
})
.controller("State1Ctrl", function($scope, $state) {
  console.log($scope.previousState, $scope.previousState.name);
})
.controller("State2Ctrl", function($scope, $state) {
  console.log($scope.previousState, $scope.previousState.name);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.