Mystery of Transclusion – Angular JS

Definition of transclusion – The inclusion of a document or part of a document into another document by reference. example are including styles.css in html page, or server side include which injects HTML fragment in a document.

In angular JS you typically custom fragment through directives and that’s where transclusion is important from angular perspective.

Two key features are provided by AngularJS to support transclusion. The first is a property that is used in directives named transclude. When a directive supports transclusion this property is set to true. The second is a directive named ng-transclude that is used to define where external content will be placed in a directive’s template. The directive code that follows uses these two AngularJS features to enable transclusion.

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


var myCustomApp = angular.module('myApp',[]);
myCustomApp.directive('customDirectiveElement', function(){
    return {
        template: 'This is my custom directive element content'

This will result in rendering

Notice that the content of your original element will be lost (or better said, replaced), button and href are gone

<a href="#">Home</a>

So, what if you want to keep your button… and href.. in the DOM? You’ll need something called transclusion. The concept is pretty simple: Include the content from one place into another.

So with transclusion the directive should look like this

myCustomApp.directive('customDirectiveElement', function(){
               restrict: 'E',
               transclusion: true,
               template: 'This is my custom directive element content 
} });

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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s