Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

element.replaceWith in link function

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?

like image 827
harishr Avatar asked Mar 09 '14 10:03

harishr


1 Answers

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.

like image 190
lib3d Avatar answered Sep 25 '22 08:09

lib3d