我有这个问题&我无法找到它的解决方案。 这是我尝试路由到可变URL路由的代码示例
$routeProvider.when('/Book', {
template: 'examples/book.html',
controller: BookCntl,
});
$routeProvider.when('/Book/chapter01', {
template: 'examples/chapter01.html',
controller: ChapterCntl,
});
如果我想修改网址,直到/Book/chapter
和01
成为变量。就像用户将02
或03
更改为100
一样。我是否需要编写$routeProvider
100次或者可以是一个简单的解决方案,我可以将数字部分用作变量并编写单$routeProvider
来处理01
到{{1} }?
答案 0 :(得分:2)
不,您不需要添加100个单独的路径定义。您可以通过添加/:some_variable
向您的网址模板添加变量,然后使用$routeParams
服务获取该变量。
$routeProvider.when('/Book/chapter/:chapterid', {
templateUrl: 'examples/chapter-view.html',
controller: ChapterCntl,
});
然后将$routeParams
注入您的控制器:
function ChapterCntl($routeParams) {
var chapterId = $routeParams.chapterid;
//use the id to fetch content.
}
看起来每个章节都有不同的html页面。如果是这种情况,您可以将函数设置为template
字段以生成html文件的路径:
$routeProvider.when('/Book/chapter/:chapterid', {
template: function(routeParams) {
var id = routeParams.id;
return 'examples/chapter'+id+'.html';
},
controller: ChapterCntl,
});
如果您是通过服务从API获取数据,那么使用resolve
字段可能会很有用。 resolve字段将加载数据并可注入控制器。这意味着在转换到新路线之前将加载数据。
$routeProvider.when('/Book/chapter/:chapterid', {
templateUrl: 'examples/chapter-view.html',
controller: ChapterCntl,
//Will run the below function before transitioning into new route.
resolve: {
chapter: function($routeParams, chaptersDataService) {
var id = $routeParams.chapterid;
return chaptersDataService.getChapter(id);
}
}
});
将章节注入你的控制器:
function ChapterCntl($scope, chapter) {
$scope.chapter = chapter;
console.log( chapter );
}
答案 1 :(得分:0)
您是否考虑过UI路由提供商?你可以很容易地使用stateparams ..
$stateProvider
.state('book.chapter', {
url: "/book/chapter/:chapterId",
templateUrl: 'book.chapter.detail.html',
controller: function ($stateParams) {
....
}
})
来源: https://github.com/angular-ui/ui-router/wiki/url-routing#url-parameters http://angular-ui.github.io/ui-router/site/#/api/ui.router.state。$ stateProvider
你也可以坚持使用routeprovider,方式与其他答案中建议的方式略有不同。
$routeProvider.when('/Book/:chapter', {
templateUrl : { function (dynamicUrl) {
return '/Book/' + dynamicUrl.chapter + '.html';
},
controller: 'ChapterCntl'
});