Javascript 根据用户输入在Angular指令中设置模板或模板URL

Javascript 根据用户输入在Angular指令中设置模板或模板URL,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我有这样的简单指令: app.directive('sample',function(){ return{ restrict:'E', template:'<a href="#">Hello sample</a>', templateUrl:'' } }); <sample template="some url"></sample> 使用templateUrl,但如果没有设置,则使用指令中的默认模板我建

我有这样的简单指令:

app.directive('sample',function(){
 return{
           restrict:'E',
    template:'<a href="#">Hello sample</a>',
    templateUrl:''
 }
});
<sample template="some url"></sample>

使用
templateUrl
,但如果没有设置,则使用指令中的默认模板

我建议使用
transclude

app.directive('sample',function(){
    return {
       restrict:'E',
       transclude: true,
       template:'<a href="#">Hello sample <div ng-transclude></div></a>
    };
});
app.directive('sample',function(){
返回{
限制:'E',
是的,
模板:'
};
});
HTML


template
templateUrl
可以指定为包含两个参数的函数-
tElement
tAttrs

一种简单的方法是移动默认模板并在
templateUrl
函数中执行逻辑:

app.directive("sample", [
  function() {

    var defaultTemplate = 'default.html';

    return {
      restrict: 'E',
      templateUrl: function (tElement, tAttrs) {
        return tAttrs.template || defaultTemplate;
      }
    }
  }
]);
演示

app.directive("sample", [
  function() {

    var defaultTemplate = 'default.html';

    return {
      restrict: 'E',
      templateUrl: function (tElement, tAttrs) {
        return tAttrs.template || defaultTemplate;
      }
    }
  }
]);