【发布时间】:2014-05-29 16:05:33
【问题描述】:
使用ui-router,可以将$state 或$stateParams 注入控制器以访问URL 中的参数。但是,通过$stateParams访问参数只会暴露属于访问它的控制器所管理的状态及其父状态的参数,而$state.params拥有所有参数,包括任何子状态中的参数。
给定以下代码,如果我们直接加载 URL http://path/1/paramA/paramB,控制器加载时是这样的:
$stateProvider.state('a', {
url: 'path/:id/:anotherParam/',
controller: 'ACtrl',
});
$stateProvider.state('a.b', {
url: '/:yetAnotherParam',
controller: 'ABCtrl',
});
module.controller('ACtrl', function($stateParams, $state) {
$state.params; // has id, anotherParam, and yetAnotherParam
$stateParams; // has id and anotherParam
}
module.controller('ABCtrl', function($stateParams, $state) {
$state.params; // has id, anotherParam, and yetAnotherParam
$stateParams; // has id, anotherParam, and yetAnotherParam
}
问题是,为什么会有差异?是否有关于何时以及为什么应该使用或避免使用其中任何一种的最佳实践指南?
【问题讨论】:
-
如此出色的说明问题 - 谢谢你告诉我什至我想问的问题!
标签: angularjs angular-ui-router