微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AngularJS指令动态模板

对不起,也许这是一个愚蠢的问题,但我还在学习。

我试图使用基于范围值的不同模板的指令。

这是我做到目前为止,我不知道为什么不工作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:'='
        }
    };
});
1)您在HTML中传递内容作为属性。尝试这个:
element.html(getTemplate(attrs.content)).show();

代替:

element.html(getTemplate(scope.content)).show();

2)指令的数据部分正在编译,所以你应该使用别的东西。而不是数据类型,例如datan类型。

链接在这里

http://jsbin.com/mibeyotu/6/edit

原文地址:https://www.jb51.cc/angularjs/146606.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐