javascript AngularJS 监听状态改变事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31741275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS listen to state change event
提问by trialar
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.
我有一个希望很简单的问题。我用 Ionic 和 AngularJS 构建了一个小应用程序。有两种状态,其中一种是包含表单的选项卡。提交后,不应再访问表单选项卡。我试图在本地存储中编写一个布尔变量,它对我来说很好用。不幸的是,当我提交表单时,我仍然可以按下 ionic 的后退按钮或 android 硬件按钮返回表单并再次提交。我通过 ng-init 调用了一个函数,该函数在加载之前切换状态,但这仅适用于刷新页面,而不适用于状态更改。
How can I listen to a state change? Do you have a better solution?
我怎样才能听到状态变化?你有更好的解决方案吗?
回答by Freezystem
It's quite easy actually, UI-router give you access to 3 differents state listener :
实际上很容易,UI-router 让你可以访问 3 个不同的状态监听器:
$rootScope.$on('$stateChangeStart',myFunc)
-> fires when state is changing
$rootScope.$on('$stateChangeStart',myFunc)
-> 状态改变时触发
$rootScope.$on('$stateChangeSuccess', myFunc)
-> fires when state has changed successfully
$rootScope.$on('$stateChangeSuccess', myFunc)
-> 当状态改变成功时触发
$rootScope.$on('$stateChangeError', myFunc)
-> fires when state change has failed
$rootScope.$on('$stateChangeError', myFunc)
-> 当状态改变失败时触发
Then you can disallow the access to one page using the resolve attribute of your state by associating it to a promise. see doc
然后,您可以通过将状态与承诺相关联,使用状态的 resolve 属性禁止对页面的访问。看文档
If the promise is resolved, access is granted else access is denied.
如果承诺得到解决,则授予访问权限,否则拒绝访问。