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 Answers1

5

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

Marcin Dusza
  • 412
  • 3
  • 10
  • 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 –  Oct 11 '16 at 11:05
  • 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](https://github.com/christopherthielen/ui-router-extras) [DOCS](http://christopherthielen.github.io/ui-router-extras/#/previous) Edit: Just to add, this service also uses $rootScope ;) – Marcin Dusza Oct 11 '16 at 11:27
  • 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. – charliebeckwith Nov 10 '16 at 19:18