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:

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

will result in this render:

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

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:

This would render:

In conclusion, you basically use transclude when you want to preserve the contents of an element when you’re using a directive.

You can play around with this code here

  • http://branchandbound.net/ Sander Mak

    Transcludes are awesome indeed! By the way, your template inside the blogpost is missing the ng-transclude directive (but your JSFiddle has it). Might be confusing for some readers…

  • http://www.odiseo.net/ odiseo42

    Thanks for noticing it! Indeed WordPress messed with me when I copied that from StackOverflow, but now it’s all fixed, thanks!