angularjs – 尝试基于常量在控制器中动态设置templateUrl
我想根据我在
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) { } }); }]);
我创建了一个
plunker here
你几乎就在那里,只是语法是’templateProvider’: .state('home',{ url: '/home',(THIS WORKS) // templateUrl: function(CONFIG) { templateProvider: function(CONFIG) { ... 来自doc的片段: Templates
所以在我们的例子中,那将是实现: $stateProvider .state('home',{ url: '/home',(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) { } }); 检查examle here 还检查: > Angular UI Router: decide child state template on the basis of parent resolved object (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |