Atula Atula - 7 months ago 115
Javascript Question

Detect specific app.state change in Ionic

Is there any method to detect Particular states change only like in my case
I want to run a function only if we go from app.state 1 to app.state 2.
controller.js

if(app.state1 to app.state2) {
$scope.run();
}


I have searched too but found nothing related to this.

Regards.

Answer

Ionic routes used angular ui-router therefore event callbacks are used in the same way:

ui-router

Where appropriate:

$rootScope.$on('$stateChangeStart', function(ev, toState, toParams, fromState, fromParams){
    if(toState.name == 'stateA' && fromState.name == 'stateB') {
        // run your code
        $scope.run();
    }
});

(UPDATE)

if you need to ask for more than one state:

$rootScope.$on('$stateChangeStart', function(ev, toState, toParams, fromState, fromParams){

    var states = ['stateB', 'stateC', 'stateD'];

    if(toState.name == 'stateA' && states.indexOf(fromState.name) > -1) {
        // run your code
        $scope.run();
    }
});