Mer*_*ott 113 angularjs angular-ui-router
使用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
}
Run Code Online (Sandbox Code Playgroud)
问题是,为什么差异?是否有关于何时以及为何使用或避免使用其中任何一种的最佳实践指南?
Mat*_*Way 64
文档重申了您的发现:https://github.com/angular-ui/ui-router/wiki/URL-Routing#stateparams-service
如果我的记忆服务,$stateParams比原来的介绍晚了$state.params,似乎是一个简单的助手注射器,以避免连续写$state.params.
我怀疑是否有任何最佳实践指南,但背景对我来说是胜利的.如果您只是想访问收到的URL中的params,那么请使用$stateParams.如果您想了解关于状态本身的更复杂的事情,请使用$state.
bbr*_*own 19
使用的另一个原因$state.params是基于非URL的状态,(在我看来)是非常糟糕的,并且非常强大.
我只是在谷歌搜索关于如何通过状态而不必在URL中公开它并在SO上的其他地方回答了问题时发现了这一点.
基本上,它允许这种语法:
<a ui-sref="toState(thingy)" class="list-group-item" ng-repeat="thingy in thingies">{{ thingy.referer }}</a>
Run Code Online (Sandbox Code Playgroud)
dae*_*rin 14
编辑:这个答案是正确的版本0.2.10.正如@Alexander Vasilyev指出它在版本中不起作用0.2.14.
使用的另一个原因$state.params是当您需要提取这样的查询参数时:
$stateProvider.state('a', {
url: 'path/:id/:anotherParam/?yetAnotherParam',
controller: 'ACtrl',
});
module.controller('ACtrl', function($stateParams, $state) {
$state.params; // has id, anotherParam, and yetAnotherParam
$stateParams; // has id and anotherParam
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
185384 次 |
| 最近记录: |