最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS listen to state change event - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Jul 31, 2015 at 10:07 Hans1984 79411 silver badges24 bronze badges asked Jul 31, 2015 at 8:12 trialartrialar 1291 gold badge2 silver badges11 bronze badges 1
  • you can listen to $rootScope.$on('$stateChangeStart'), $rootScope.$on('$stateChangeSuccess') and $rootScope.$on('$stateChangeError') – Freezystem Commented Jul 31, 2015 at 8:17
Add a ment  | 

1 Answer 1

Reset to default 13

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.

发布评论

评论列表(0)

  1. 暂无评论