Pet*_*ner 6 angularjs angular-ui-router
我想根据我在angularjs bootstrap中定义的预设常量来更改与控制器关联的templateUrl.我无法弄清楚如何改变它.我已经尝试过UrlRouteProvider但是还没弄清楚如何从文件系统中拉出html.我被困在templateUrl上.
在下面的代码中,输出首先显示"svcc确实传递到第一个函数的console.out但是在templateUrl定义函数中,CONFIG是未定义的.
我愿意采取其他方式来做到这一点.
var app = angular.module('svccApp', [
'ui.router'
]);
var myConstant = {};
myConstant.codeCampType = "svcc";
app.constant("CONFIG", myConstant);
app.config(['$stateProvider', '$urlRouterProvider','CONFIG',
function ($stateProvider, $urlRouterProvider,CONFIG) {
console.log(CONFIG.codeCampType);
$stateProvider
.state('home', {
url: '/home',
//templateUrl: 'index5templateA.html', (THIS WORKS)
templateUrl: function(CONFIG) {
console.log('in templateUrl ' + CONFIG.codeCampType);
if (CONFIG.codeCampType === "svcc") {
return 'index5templateA.html';
} else {
return 'index5templateB.html';
}
},
controller: function ($state) {
}
});
}]);
Run Code Online (Sandbox Code Playgroud)
我在这里创建了一个plunker
你几乎就在那里,只是语法是'templateProvider':
.state('home', {
url: '/home',
//templateUrl: 'index5templateA.html', (THIS WORKS)
// templateUrl: function(CONFIG) {
templateProvider: function(CONFIG) {
...
Run Code Online (Sandbox Code Playgroud)
来自doc的片段:
TemplateUrl
...templateUrl也可以是返回url的函数.它需要一个预设参数stateParams,它不是注入的.TemplateProvider
或者您可以使用模板提供程序函数,该函数可以注入,可以访问本地,并且必须返回模板HTML,如下所示:
所以在我们的例子中,那将是实现:
$stateProvider
.state('home', {
url: '/home',
//templateUrl: 'index5templateA.html', (THIS WORKS)
templateProvider: function(CONFIG, $http, $templateCache) {
console.log('in templateUrl ' + CONFIG.codeCampType);
var templateName = 'index5templateB.html';
if (CONFIG.codeCampType === "svcc") {
templateName = 'index5templateA.html';
}
var tpl = $templateCache.get(templateName);
if(tpl){
return tpl;
}
return $http
.get(templateName)
.then(function(response){
tpl = response.data
$templateCache.put(templateName, tpl);
return tpl;
});
},
controller: function ($state) {
}
});
Run Code Online (Sandbox Code Playgroud)
还检查:
| 归档时间: |
|
| 查看次数: |
11576 次 |
| 最近记录: |