Understanding AngularJS transclude in directives

One of my favorite features of AngularJS are directives. They’re extremely modular and reusable components to “enhance” HTML, a different approach to regular JavaScript or JQuery widgets. I’ll write later about directives, but for now I’ll talk only about the concept of transclusion. I believe the explanation given in the official documentation is kinda obscure, and since I think transclusion is actually very useful when writing your own AngularJS directives, I’ll share an answer I gave in StackOverflow about how to understand AngularJS transclude.

Consider a directive called myDirective in an element, and that element is enclosing some other content, let’s say:

1

2

3

4

'<div my-directive>

<button>some button</button>

<a href="#">and a link</a>

</div>'

If myDirective is using a template, you’ll see that the content of
will be replaced by your directive template. So having:

1

2

3

4

5

app.directive('myDirective',function(){

return{

template:'<div class="something">This is my directive content</div>'

}

});

will result in this render:

1

'<div class="something"> This is my directive content</div>'

Notice that the content of your original element will be lost (or better said, replaced). So, say good-bye to these buddies:

1

2

'<button>some button</button>

<a href="#">and a link</a>'

So, what if you want to keep your <button>… and <a>… in the DOM? You’ll need something called transclusion. The concept is pretty simple: Include the content from one place into another. So now your directive will look something like this: