user4904589
user4904589

Reputation: 565

What is the significance of using $compile in directive definition?

Following code is similar to the one provided in this video by egghead.io` where he was building a directive for debugging.

app.directive('debug',function($compile){// injecting compiler
    return{ // DDO
        terminal:true,
        priority:1000,
        link:function($scope,$element){
            var clone = $element.clone();
            clone.removeAttr("debug");
            $element.addClass('highlight');
            var clonedElement = $compile(clone)($scope);
            $element.after(clonedElement);
        }
    };
});

My question is, what is the significance of using $compile to compile the clone and then adding clonedElement to the DOM? I tried to add(code given below) clone instead of clonedElement and it APPARENTLY does the same thing.

app.directive('debug',function($compile){// injecting compiler
    return{ // DDO
        terminal:true,
        priority:1000,
        link:function($scope,$element){
            var clone = $element.clone();
            clone.removeAttr("debug");
            $element.addClass('highlight');
            //var clonedElement = $compile(clone)($scope);
            $element.after(clone);
        }
    };
});

Upvotes: 0

Views: 37

Answers (1)

m59
m59

Reputation: 43755

It is unlikely to matter in this limited example, but the difference is that Angular is not considering that DOM element. If the DOM element were to have directives or bindings, they will not work because Angular has not been made aware of that element. $compile is what associates a new DOM element with Angular.

Be sure to read the documentation for APIs you're unfamiliar with.

Upvotes: 1

Related Questions