AngularJS Transclusion Example Tutorial

Earlier we looked at custom directives and in this tutorial, we will discuss about the transclusion in directives.

Transclusion means the inclusion of the content of one document in another document by reference (wikipedia).

Transclusion provides a way to pass in templates to a directive and it is displayed. In the previous tutorials, we have used the template property to display the desirable templates.

Let us look at the below example to see what happens if we define a template inside the directive element.
In the following example, we have created a directive called myEmployee that displays a template.

app.js

We have included an element inside the my-employee directive in index.html file.

app.js

You will see the following output in your browser.
transcludeDisabled

The content inside my-employee directive is not displayed. AngularJS provides tranclude property to support the transclusion in directive. We will see this in the following section using the above example.

Transclusion in Directive Example

AngularJS provides two key features to support transclusion. The first one is a property that is used in directives named transclude and setting this to true enables the transclusion.The second is a directive named ng-transclude that is used to define where external content will be placed in a directive’s template. You can see the use of these two features in the following example.

We have modified the above example to support transclusion simply by adding a transclude property to the myEmployee directive and it is set to true.

app.js

The ng-transclude is a directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion. The template we pass in to the directive will replace the element with ng-transclude directive. In this example, we have replaced a div element without any content with meaningful div content.

app.js

You will see the following output on your browser.

trancludeEnabled-

That’s all for now and we will see more AngularJS features in the coming posts.

By admin

Leave a Reply