trialar
trialar

Reputation: 129

AngularJS listen to state change event

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?

Upvotes: 3

Views: 20404

Answers (1)

Freezystem
Freezystem

Reputation: 4874

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.

Upvotes: 13

Related Questions