Javascript 如何在angular js中执行变量路由
我有这个问题&我找不到解决办法。 这是我试图路由到可变URL路由的代码示例Javascript 如何在angular js中执行变量路由,javascript,angularjs,routing,angular-ui-router,single-page-application,Javascript,Angularjs,Routing,Angular Ui Router,Single Page Application,我有这个问题&我找不到解决办法。 这是我试图路由到可变URL路由的代码示例 $routeProvider.when('/Book', { template: 'examples/book.html', controller: BookCntl, }); $routeProvider.when('/Book/chapter01', { template: 'examples/chapter01.html', controller: ChapterCntl, });
$routeProvider.when('/Book', {
template: 'examples/book.html',
controller: BookCntl,
});
$routeProvider.when('/Book/chapter01', {
template: 'examples/chapter01.html',
controller: ChapterCntl,
});
如果我想修复url,直到
/Book/chapter
和01
可以是一个变量。如用户更改02
或03
直到100
。我是否需要将$routeProvider
写入100次,或者可以是一个简单的解决方案,其中我可以使用数字部分作为变量,并编写单个$routeProvider
来处理01
到100
您考虑过UI路由提供商吗?您可以轻松地使用stateparms
$stateProvider
.state('book.chapter', {
url: "/book/chapter/:chapterId",
templateUrl: 'book.chapter.detail.html',
controller: function ($stateParams) {
....
}
})
资料来源:
$stateProvider
您也可以使用routeprovider,其方式与其他答案中的建议略有不同
$routeProvider.when('/Book/:chapter', {
templateUrl : { function (dynamicUrl) {
return '/Book/' + dynamicUrl.chapter + '.html';
},
controller: 'ChapterCntl'
});
不需要,您不需要添加100个单独的管线定义。通过添加
/:some_variable
向url模板添加变量,然后使用$routeParams
服务获取该变量
例子
然后将$routeParams
注入控制器:
function ChapterCntl($routeParams) {
var chapterId = $routeParams.chapterid;
//use the id to fetch content.
}
function ChapterCntl($scope, chapter) {
$scope.chapter = chapter;
console.log( chapter );
}
看起来每个章节都有不同的html页面。如果是这种情况,您可以在模板
字段中设置一个函数来生成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($routeParams) {
var chapterId = $routeParams.chapterid;
//use the id to fetch content.
}
function ChapterCntl($scope, chapter) {
$scope.chapter = chapter;
console.log( chapter );
}