我。双重状态映射(控制器、视图的重用)
注意:这是原始答案,展示了如何解决两种状态的问题。下面是另一种方法,对Geert
的评论做出反应
有一个带有工作示例的plunker。假设我们有这两个对象(在服务器上)
var articles = [
{ID: 1, Title : 'The cool one', Content : 'The content of the cool one',},
{ID: 2, Title : 'The poor one', Content : 'The content of the poor one',},
];
我们想使用 URL 作为
// by ID
../article/1
../article/2
// by Title
../article/The-cool-one
../article/The-poor-one
然后我们可以创建这个状态定义:
// the detail state with ID
.state('articles.detail', {
url: "/{ID:[0-9]{1,8}}",
templateUrl: 'article.tpl.html',
resolve : {
item : function(ArticleSvc, $stateParams) {
return ArticleSvc.getById($stateParams.ID);
},
},
controller:['$scope','$state','item',
function ( $scope , $state , item){
$scope.article = item;
}],
})
// the title state, expecting the Title to be passed
.state('articles.title', {
url: "/{Title:[0-9a-zA-Z\-]*}",
templateUrl: 'article.tpl.html',
resolve : {
item : function(ArticleSvc, $stateParams) {
return ArticleSvc.getByTitle($stateParams.Title);
},
},
controller:['$scope','$state','item',
function ( $scope , $state , item){
$scope.article = item;
}],
})
正如我们所见,诀窍在于 Controller 和 Template (templateUrl) 是相同的。我们只需询问服务ArticleSvc 至getById() 或getByTitle()。解决后,我们可以处理退回的项目...
更详细的plunker是here
二。别名,基于原生 UI-Router 功能
注意:此扩展会对 Geert 适当的评论做出反应
所以,有一个UI-Router 内置/原生方式用于路由别名。它被称为
我创建了工作plunker here。首先,我们只需要一个状态定义,但对 ID 没有任何限制。
.state('articles.detail', {
//url: "/{ID:[0-9]{1,8}}",
url: "/{ID}",
我们还必须实现一些映射器,将标题转换为 id (别名映射器)。那将是新的文章服务方法:
var getIdByTitle = function(title){
// some how get the ID for a Title
...
}
现在$urlRouterProvider.when()的力量
$urlRouterProvider.when(/article\/[a-zA-Z\-]+/,
function($match, $state, ArticleSvc) {
// get the Title
var title = $match.input.split('article/')[1];
// get some promise resolving that title
// converting it into ID
var promiseId = ArticleSvc.getIdByTitle(title);
promiseId.then(function(id){
// once ID is recieved... we can go to the detail
$state.go('articles.detail', { ID: id}, {location: false});
})
// essential part! this will instruct UI-Router,
// that we did it... no need to resolve state anymore
return true;
}
);
就是这样。这个简单的实现会跳过错误、错误的标题...处理。但这无论如何都有望实现...Check it here in action