我有以下指令:
mod.directive('uiSearchInput', function () {
return {
restrict: 'A',
template:
'<div class="ui-search-input">' +
'<i class="i i-search ui-search-input__icon"></i><div ng-transclude class="ui-search-input__field"></div>' +
'</div>',
transclude: 'element',
replace: true
};
});
我想像这样使用:
<input type="text" placeholder="Search internal tags"
ui-search-input
ng:model="tagQuery"
ng:change="showCandidateTags()">
嵌入成功工作,但 Angular 最终将我原始 input
元素中的属性放在模板的 root
元素上以及 嵌入的 input
元素。请参阅此屏幕截图:
注意到根 div
和嵌套的 input
元素如何都具有 ngModel
集以及其他属性?
此重复似乎导致我的应用程序出现问题。有可能完全避免这种情况吗?
最佳答案
正如我在评论中提到的,这实际上是在指令中使用模板时的预期结果,引用自 Angular 文档:
template - replace the current element with the contents of the HTML. The replacement process migrates all of the attributes / classes from the old element to the new one.
解决此问题的一种可能方法是从编译函数中的包含元素中删除所有不需要的属性:
compile: function(tElem, tAttrs) {
['ngModel', 'ngChange', 'type', 'placeholder'].forEach(function(name) {
tElem.removeAttr(tAttrs.$attr[name]);
});
}
关于javascript - Angular 中的 Transclude 元素导致重复属性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18124522/