i have seen different example for rending an element in the link function
example one:
var template = '<span><input type="text" ng-model="ngModel"></span>';
element.html(template);
$compile(element.contents())(scope);
example two:
var template = '<span><input type="text" ng-model="ngModel"></span>';
element.html(template);
var el = $compile(element.contents())(scope);
element.replaceWith(el);
i had tried 2-3 simple directives which works even without replacing the element. so what is the use case for the "element.replaceWith(el)". When is it necessary to user "element.replaceWith(el)" at the end of the link function?
Replacement is actually optional, and the final result won't be exactly the same:
Your first example: the element with your directive has the span as its only child
Your second example: the element with your directive is finally replaced with the span -> one level less in the 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With