jac*_*cob 5 angular-ui angular-ui-router
我正在尝试使用可选参数创建路由; 显然ui.route没有这种能力(即使ngRoute几乎永远存在).所以相反,我已将它们指定为查询参数,并尝试将它们转换为适当的RESTful网址,该网址将针对$ stateParams展开:
在ngRouter语法中,我将指定: /:resource/:collection?/:type?/:index?
在ui.router中,我将其指定为: /:resource?collection&type&index
我试图用一个返回路径的函数动态地翻译它(尝试使用.when()和.rule()):
$urlRouterProvider
.when('' , '/index')
.when('/', '/index')
.when( urlMatcher.source , function convertToREST( $match , $stateParams )
{
var params = [$match.resource];
if ( angular.isDefined($match.collection) ) params[1] = $match.collection;
if ( angular.isDefined($match.type) ) params[2] = $match.type;
if ( angular.isDefined($match.index) ) params[3] = $match.index;
var result = '/' + params.join('/');
return result;
} )
.otherwise( '/404' );
Run Code Online (Sandbox Code Playgroud)
上面导致没有渲染视图(删除第3 .when()和视图渲染就好了).
并手动:
$urlRouterProvider
.when('' , '/index')
.when('/', '/index')
.when( '/:resource?collection' , '/:resource/:collection' )
.otherwise( '/404' );
Run Code Online (Sandbox Code Playgroud)
这显然导致循环迭代.我从ui-router的示例应用程序中获得了这个手动创意:state.js#L16.我看到的唯一区别是我从一个参数开始,但我不明白这是什么重要.
如果我正确理解了这个问题,那么您想要实现的是网址的可选参数。
ui.router 确实提供了这个功能,有几个选项用于指定参数。基本参数如下所示:
$stateProvider
.state('contacts.detail', {
url: "/contacts/:contactId",
templateUrl: 'contacts.detail.html',
controller: function ($stateParams) {
// If we got here from a url of /contacts/42
expect($stateParams).toBe({contactId: "42"});
}
})
Alternatively you can also use curly brackets:
// identical to previous example
url: "/contacts/{contactId}"
Run Code Online (Sandbox Code Playgroud)
如果您是嵌套状态,则必须解析父路由中的参数,文档中提供了类似的情况:
$stateProvider.state('contacts.detail', {
url: '/contacts/:contactId',
controller: function($stateParams){
$stateParams.contactId //*** Exists! ***//
}
}).state('contacts.detail.subitem', {
url: '/item/:itemId',
controller: function($stateParams){
$stateParams.contactId //*** Watch Out! DOESN'T EXIST!! ***//
$stateParams.itemId //*** Exists! ***//
}
})
Run Code Online (Sandbox Code Playgroud)
解决办法是在父路由中使用resolve语句
$stateProvider.state('contacts.detail', {
url: '/contacts/:contactId',
controller: function($stateParams){
$stateParams.contactId //*** Exists! ***//
},
resolve:{
contactId: ['$stateParams', function($stateParams){
return $stateParams.contactId;
}]
}
}).state('contacts.detail.subitem', {
url: '/item/:itemId',
controller: function($stateParams, contactId){
contactId //*** Exists! ***//
$stateParams.itemId //*** Exists! ***//
}
})
Run Code Online (Sandbox Code Playgroud)
如图所示,通过在控制器中使用$stateParams获取结果,如下所示
$stateParams.contactId
Run Code Online (Sandbox Code Playgroud)
您可以参考文档了解更多详细信息。
| 归档时间: |
|
| 查看次数: |
3352 次 |
| 最近记录: |