问题描述
我正在调查是否可以获得标题所说的内容.这是我的想法.
i'm investigating if i can have what the title says.Here's my thought.
假设我有这样的路线:
.when('/', {
templateUrl : 'partials/homepage.html',
})
.when('/test', {
templateUrl : 'partials/test.html',
})
.when('/page/:pageID', {
templateUrl : 'partials/page.html',
})
.when('/page/single/:pageID', {
templateUrl : 'partials/page-single.html',
})
直到现在,我有机会在路由中添加 templateUrl 以及控制器详细信息,并且一切正常.
Until now i had the opportunity to add the templateUrl as also the controller details in the route and everything was working just fine.
现在应用程序已更改,只有一个控制器包含所需的所有信息,并且必须保留为一个控制器.路线将是这样的:
Now the app is changed and there is only one controller with all the information needed and must remain one controller. And the routes will be something like that:
.when('/:templateName/:pageID', {
controller: 'myCtrl'
})
我可以通过获取 templateName 参数从控制器设置模板 id 吗?如果是这样,最后一个路由示例/page/single/:pageID 怎么样?我怎么知道路线中有第二个选项?
Can i set from the controller the template id by getting the templateName parameter? And if so how about the last route example /page/single/:pageID? How can i know that there is a second option in route?
我可以使用 templateName 参数并通过 $routeChangeSuccess 方法查看它的变化,但我找不到任何方法来即时设置模板.
I can take the templateName parameter and see it changing with the $routeChangeSuccess method but i cannot find any way to set the template on the fly.
有什么想法吗?
推荐答案
一种解决方案可能是以下一种:
One solution could be the following one:
angular.module('myapp', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/:templateName/:pageId', {
templateUrl: function(urlattr){
return '/pages/' + urlattr.templateName + '.html';
},
controller: 'YourCtrl'
});
}
]);
来自 AngularJs 1.3 文档:
templateUrl
– {string
|function()
} – 返回 html 模板路径的路径或函数,该模板应由ngView.
如果 templateUrl 是一个函数,它将使用以下参数调用:Array.
- 通过应用当前路由从当前 $location.path()
提取的路由参数
If templateUrl is a function, it will be called with the following parameters:Array.<Object>
- route parameters extracted from the current $location.path()
by applying the current route
这篇关于AngularJS,具有不同模板但具有相同控制器的多个路由怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!