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;
}
}
}
]);