小编典典

尝试基于常量在控制器中动态设置templateUrl

angularjs

我想基于我在angularjs引导程序中定义的预设常数来更改与控制器关联的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) {
                    }
                });
        }]);

阅读 305

收藏
2020-07-04

共1个答案

小编典典

我在这里创建了一个插件,
您几乎就在那儿,只是语法是 'templateProvider'

.state('home', {
    url: '/home',
    //templateUrl: 'index5templateA.html',   (THIS WORKS)
    // templateUrl: function(CONFIG) {
    templateProvider: function(CONFIG) {
    ...

doc的片段:

范本

TemplateUrl
templateUrl也可以是返回url的函数。 它采用一个预设参数stateParams,该参数不会被注入。

TemplateProvider
或者您可以使用 模板提供程序 函数,该函数 可以被注入,可以访问locals 并且必须返回模板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) {
        }
    });

这里检查例子

2020-07-04