我有这样简单的指令:
app.directive('sample',function(){
return{
restrict:'E',
template:'<a href="#">Hello sample</a>',
templateUrl:''
}
});
我希望当用户在这样的标签中声明 templateUrl
时:
<sample template="some url"></sample>
使用 templateUrl
但如果没有设置,则使用指令中的默认模板
最佳答案
template
和 templateUrl
可以指定为带有两个参数的函数 - tElement
和 tAttrs
。
一种简单的方法是移动您的默认模板并在 templateUrl
函数中执行您的逻辑:
app.directive("sample", [
function() {
var defaultTemplate = 'default.html';
return {
restrict: 'E',
templateUrl: function (tElement, tAttrs) {
return tAttrs.template || defaultTemplate;
}
}
}
]);
关于javascript - 根据用户输入在 Angular 指令中设置模板或 templateUrl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23333956/