AngularJS listen to state change event

18,753

It's quite easy actually, UI-router give you access to 3 differents state listener :

$rootScope.$on('$stateChangeStart',myFunc) -> fires when state is changing

$rootScope.$on('$stateChangeSuccess', myFunc) -> fires when state has changed successfully

$rootScope.$on('$stateChangeError', myFunc) -> fires when state change has failed

Then you can disallow the access to one page using the resolve attribute of your state by associating it to a promise. see doc

If the promise is resolved, access is granted else access is denied.

Share:
18,753
trialar
Author by

trialar

Updated on June 13, 2022

Comments

  • trialar
    trialar almost 2 years

    I have a, hopefully, simple question. I've built a small App with Ionic and AngularJS. There are two States, one of them is a tab containing a form. When submitted the form tab shouldn't be accessible anymore. I've tried to write a boolean variable in local storage and it works fine for me. Unfortunately when I submit the form I can still push the back button of ionic or the android hardwarebutton to go back to the form and submit again. I called a function via ng-init that switches the state before loading but this only works with refreshing the page, not at the state change.

    How can I listen to a state change? Do you have a better solution?

  • Nick Grealy
    Nick Grealy over 6 years
    NOTE: State change events are deprecated, DISABLED and replaced by Transition Hooks as of version 1.0 - ui-router.github.io/guide/ng1/…