Qll*_*lli 6 angularjs angular-ui-router
我如何使用从我的数据库中获取的名称作为templateUrl文件名?
我试过这个:
$stateProvider.state('/', {
url: '/',
views: {
page: {
controller: 'HomeCtrl',
templateProvider: function($templateFactory, $rootScope) {
console.log("$rootScope.template")
return $templateFactory.fromUrl('/templates/' + $rootScope.template);
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
如果我的$ rootScope.template来自数据库查询,那似乎不起作用.不知道为什么,但它不起作用.
如果在我的控制器中我做$ rootScope.template ="whatever.html"一切正常,但如果我从数据库查询模板,根本没有任何事情发生.templateProvider中的console.log("$ rootScope.template")没有给我任何东西(查询本身工作得很好).
查询是否只需要太长时间,因此它没有为路由器做好准备或者在这里发生了什么?
我做错了,我该怎么办呢?
正如本问答中所讨论的:Angular UI Router:根据父解析对象决定子状态模板,我们可以这样做
这可能是"来自服务器/数据库加载模板名称"的服务角色:
.factory('GetName', ['$http', '$timeout',
function($http, $timeout) {
return {
get : function(id) {
// let's pretend server async delay
return $timeout(function(){
// super simplified switch... but ...
var name = id == 1
? "views.view2.html"
: "views.view2.second.html"
;
return {templateName : name};
}, 500);
},
};
}
]);
Run Code Online (Sandbox Code Playgroud)
然后templateProvider定义看起来像这样:
views: {
"page": {
templateProvider: function($http, $stateParams, GetName) {
// async service to get template name from DB
return GetName
.get($stateParams.someSwitch)
// now we have a name
.then(function(obj){
return $http
// let's ask for a template
.get(obj.templateName)
.then(function(tpl){
// haleluja... return template
return tpl.data;
});
})
},
Run Code Online (Sandbox Code Playgroud)
代码应该是自我解释的.有关更多详细信息,请查看此答案及其附件
| 归档时间: |
|
| 查看次数: |
10214 次 |
| 最近记录: |