【问题标题】:Angular: Variable template inside directiveAngular:指令内的变量模板
【发布时间】:2016-08-31 12:35:54
【问题描述】:

在我的 Angular 模板中,我使用如下属性指令:

HTML:

<div id="my-template-one" my-template-directive></div>

JS:

// ...
.directive('myTemplateDirective', ['myconfig', function (myconfig) {
        return {
            templateUrl: myconfig.TEMPLATE_PATH + 'my-template-one.html',
            controller: function ($scope, $rootScope) {
                // code
            },
            controllerAs: 'dir'
        }
    }]);

为了在另一个页面上包含另一个模板my-template-two.html,我想使用相同的指令。我不想重复该指令。如何将模板作为变量传递?

另一个页面上的HTML:

<div id="my-template-two" my-template-directive></div>

我的目标是,我可以通过某种方式告诉我的指令在调用此 HTML 时呈现 my-template-two.html

【问题讨论】:

    标签: javascript angularjs templates angularjs-directive


    【解决方案1】:

    templateUrl 属性值可能是一个函数,它接受两个参数 tElementtAttrs 并返回一个字符串值:

    app.directive('myTemplateDirective', ['myconfig', function (myconfig) {
        return {
            templateUrl: function (tElem, tAttrs) {
                var template = "my-template-one.html";
                if (tAttrs.use) {
                    template = tAttrs.use;
                };             
                return myconfig.TEMPLATE_PATH + template;
            },
            controller: function ($scope, $rootScope) {
                // code
            },
            controllerAs: 'dir'
        }
    }]);
    

    用法

    <div my-template-directive use="my-template-two.html"> </div>
    

    欲了解更多信息,请参阅AngularJS Comprehensive Directive API -- template

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      相关资源
      最近更新 更多