AngularJS 指令动态模板

标签 angularjs angularjs-directive angularjs-scope

我正在尝试根据范围值使用不同的模板制作指令。

这是我到目前为止所做的,我不知道为什么不起作用 http://jsbin.com/mibeyotu/1/edit

HTML 元素:

<data-type content-attr="test1"></data-type>

指令:

var app = angular.module('myApp', []);

app.directive('dataType', function ($compile) {

    var testTemplate1 = '<h1>Test1</h1>';
    var testTemplate2 = '<h1>Test2</h1>';
    var testTemplate3 = '<h1>Test3</h1>';

    var getTemplate = function(contentType){

        var template = '';

        switch(contentType){
            case 'test1':
                template = testTemplate1;
                break;
            case 'test2':
                template = testTemplate2;
                break;
            case 'test3':
                template = testTemplate3;
                break;
        }

        return template;
    }; 

    var linker = function(scope, element, attrs){
        element.html(getTemplate(scope.content)).show();
        $compile(element.contents())(scope);
    };

    return {
        restrict: "E",
        replace: true,
        link: linker,
        scope: {
            content:'='
        }
    };
});

最佳答案

您可以将指令定义对象的 template 属性设置为将返回动态模板的函数:

restrict: "E",
replace: true,
template: function(tElement, tAttrs) {
    return getTemplate(tAttrs.content);
}

请注意,您此时无权访问作用域,但您可以通过 tAttrs 访问属性。

现在您的模板已在编译阶段之前确定,您无需手动编译它。

关于AngularJS 指令动态模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23065165/

相关文章:

javascript - angularjs - 选择的 ng-model 索引

jquery - 如何在 AngularJS 中监听 jQuery 事件

javascript - 使用模板后使用 Angular 获取元素属性值

javascript - 需要隐藏url中的变量值

javascript - 验证消息到指令 - AngularJS

angularjs - 将参数传递给多个 AngularJS 指令实例?

angularjs - 语法危险 : Token '}' is unexpected, 期待 [ :] at column 35 of the expression [yourSelectRadio={item. 极化}]

forms - 如何滚动到表单中的错误?

data-binding - AngularJS:如果元素具有 ngModel 和自定义指令,则两种方式数据绑定(bind)失败

AngularJS : How to change scope value from isolated scope within directive