我看到了在链接功能中放租元素的其他示例
例子一:
var template = '<span><input type="text" ng-model="ngModel"></span>';
element.html(template);
$compile(element.contents())(scope);
示例二:
var template = '<span><input type="text" ng-model="ngModel"></span>';
element.html(template);
var el = $compile(element.contents())(scope);
element.replaceWith(el);
我尝试了2-3个简单的指令,即使不替换元素也能正常工作。那么“element.replaceWith(el)”的用例是什么。何时需要在链接功能的末尾使用“element.replaceWith(el)”?
最佳答案
替换实际上是可选的,最终结果将不完全相同:
您的第一个示例:具有指令的元素的跨度为其唯一的子级
您的第二个示例:最终将带有指令的元素替换为span->在DOM中减少一级。
All is about what you want in the DOM at the end. If you consider the original container with the directive is a useless wrapper only declaring a component, you will want to unwrap the content.
关于angularjs - 链接函数中的element.replaceWith,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22280841/