Angularjs   发布时间:2019-10-10  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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
> Angular and UI-Router,how to set a dynamic templateUrl

大佬总结

以上是大佬教程为你收集整理的angularjs – 尝试基于常量在控制器中动态设置templateUrl全部内容,希望文章能够帮你解决angularjs – 尝试基于常量在控制器中动态设置templateUrl所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。