Accessing Scope onExit of Angular-UI-Router?

user2227400 picture user2227400 · Jan 26, 2016 · Viewed 8.9k times · Source

I'am looking for the following possibility:

$stateProvider.state('user', angularAMD.route({
        url: '/user/:id',
        templateUrl: 'views/user.html',
        controllerUrl: 'views/user',
        controller: 'UserCtrl',
        onExit: function () {
            alert ("exit user");
           // call scope function saveCurrentStateData();

        }
    }));

saveCurrentStateData() stores some scope data (e.g. $scope.my.data) via a defined REST-Service at the backend.

EDIT: Can you give me a solution without $scope.$on ('destroy',.. maybe with resolve property of ui-router ? Why can't I use onExit, why it is here?

Answer

Joel Hernandez picture Joel Hernandez · Jan 26, 2016

You can listen to the $destroy $scope event of your controller

var UserCtrl = function ($scope) {
    $scope.$on('$destroy', function() {
        // Do your cleanup here or call a function that does
    });
};

And for a bit of reference of when does controller get instantiated and destroyed on ui-router, see this question

EDIT 1: If you want to access your $state parameters you can listen to the $stateChangeStart or $stateChangeSuccess events and do something like this

$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState,fromParams) {
            if(fromState.name == 'yourstate'){
                // Here is your param
                console.log(fromParams.stateid);
            }
        });

EDIT 2: The reason that you cannot use onExit is because by the time that method is called the state has been already changed. However this is fixed in the next major version (1.0) by adding an injectable service called $transition$ which will provide access to the parameters of the state, you can read more about that here