我想知道如何动态地将特性或属性添加到模板中的特定标记中。我的指令是这样的:
app.directive('myDirective', function() {
return {
restrict: 'A',
template:
'<div><label>Label: </label><input id="my-id" type="text" attr="attrValue"/></div>'
};
});
问题 1:如何将 attr="attrValue"
专门放置在 input
元素/标记上?
假设我想写:
<my-directive ... readonly></my-directive>
问题 2:如何将 readonly
属性传递给模板中的 input
元素?
app.directive('myDirective', function() {
return {
restrict: 'A',
template:
'<div><label>Label: </label><input id="my-id" type="text" readonly/></div>'
};
});
最佳答案
指令配置的 template
属性可以是一个函数,它接收元素和属性作为参数并返回模板 ( see documentation )。然后,您可以在构建模板时使用这些数据:
.directive('...', function () {
return {
template: function (tElement, tAttrs) {
return '... <input ...' + (tAttrs.readonly ? ' readonly' : '') + '> ...';
},
// ...
};
});
关于angularjs - 根据元素属性调整指令模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27542427/