将变量引用为指令模板内容

时间:2013-09-30 11:14:36

标签: angularjs

是否可以将字符串变量设置为模板的内容? 我想根据范围选择两个不同的模板。 像这样:

define(['app'], function(app){
    app.directive('logstorelist', function(){
        var temp="";
        return{
            scope: true,
            restrict: 'A',
            link: function(s, e, a){
                if(a=="a")
                    temp = "<a>tempA</a>";
                else
                    temp = "<div>temp</div>";
            },
            replace: true,
            template: temp
        }
    })
});

这样的事情可能吗?

1 个答案:

答案 0 :(得分:1)

您只能使用一个模板并使用ng-switch根据您的范围变量加载内容(如果您不介意额外的<span>):

define(['app'], function(app){
    app.directive('logstorelist', function(){
        var temp="";
        return{
            scope: true,
            restrict: 'A',
            link: function(s, e, a){
                s.temp = a;
            },
            replace: true,
            template: 
            ' <span ng-switch="temp">
                <a ng-switch-when="a">tempA</a>
                <div ng-switch-default>temp</div>
            </span>'
        }
    })
});