javascript 可以在“视图”中访问 $stateParams 但不能在控制器中访问
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21113623/
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
Can access $stateParams in "view" but not in the controller
提问by ericbae
I'm going through the AngularUI Router sample app in http://angular-ui.github.io/ui-router/sample/#/
我正在浏览http://angular-ui.github.io/ui-router/sample/#/ 中的 AngularUI 路由器示例应用程序
I think I understand in general what is going on and have been able to implement something similar for my app.
我想我大致了解正在发生的事情,并且已经能够为我的应用程序实现类似的功能。
My question is that it seems that you can access $stateParams
from "View" files (e.g. https://github.com/angular-ui/ui-router/blob/master/sample/contacts.html- where it refers to $stateParam
), but when I access the $stateParams
in the controller, it returns an empty object. (https://github.com/angular-ui/ui-router/blob/master/sample/states.js#L83)
我的问题是,您似乎可以$stateParams
从“查看”文件(例如https://github.com/angular-ui/ui-router/blob/master/sample/contacts.html- 它指的地方$stateParam
)访问,但是当我访问$stateParams
控制器中的 时,它返回一个空对象。( https://github.com/angular-ui/ui-router/blob/master/sample/states.js#L83)
So I guess what I'm trying to do is access the state of the child view in the parent view controller via $stateParam
s, but it's an empty object.
所以我想我想要做的是通过$stateParam
s访问父视图控制器中子视图的状态,但它是一个空对象。
Instead, I can get the state by doing $state.params.PARAMETER_NAME
.
相反,我可以通过执行$state.params.PARAMETER_NAME
.
Why is that?
这是为什么?
回答by Thomas Parslow
This is by design, see https://github.com/angular-ui/ui-router/wiki/URL-Routing#two-important-stateparams-gotchas
这是设计使然,请参阅https://github.com/angular-ui/ui-router/wiki/URL-Routing#two-important-stateparams-gotchas
It seems like a good idea to me, it's not very clear code if you're accessing state params from a child view in one of its ancestors.
对我来说这似乎是一个好主意,如果您从其祖先之一的子视图访问状态参数,则代码不是很清楚。
回答by d3l33t
You could always set the params, in the parent scope
您始终可以在父作用域中设置参数
$scope.setParams = function(params) {
$scope.params = params
}
In child controller
在子控制器中
$scope.ParentController.setChildViewParams($stateParam);