3

Hello all I want to know how to make a return to the previous page in AngularJS with state.go stateParams or between two different pages I tried this but the variable is empty:

   $ctrl.next = function(){

        $state.go('modiffili', {object:'test'});

    };

and this controller of my second page :

(function (angular) {
'use strict';

modiffiliCtrl.$inject=['$state','$stateParams'];


function modiffiliCtrl($state,$stateParams) {
    var $ctrl = this;


    console.log('modiffiliController');
    console.log($state.params.object);
   $ctrl.retour = function () {
        $state.go('^');
}

I can't to use rootScope. thank you to help me !

1 Answer 1

6

You can listen to $stateChangeStart event, and save the name and params of previous state in order to be able to return to it.

$rootScope.$on('$stateChangeStart', function (event, toState, toStateParams, fromState, fromParams) {
   $rootScope.previousState = fromState;
   $rootScope.previousStateParams = fromParams;
});

And then you can call $state.go($rootScope.previousState, $rootScope.previousStateParams) if you need it

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you but my boss don't want that I use rootscope :/ with ui router isn't possible with ng-click previoustate() ? or it's the only solution ? thanks
You shouldn't be afraid of using $rootScope 'just because'. It's the only place where you can be sure that every event will eventually land. I know that it's done this way in JHipster, so I think it's pretty decent solution. On the other hand, I've found an addon to ui-router which has that feature: REPO DOCS Edit: Just to add, this service also uses $rootScope ;)
Just a note to future visitors, the broadcast events, like this, are now deprecated and not included in recent releases of ui-router. To use these events you must rebuild the project and include the state-events file.