March 6, 2015

tl;dr: Transclusion is easy to learn and easy to implement.



See key points at end of post.

When I was first learning how to create custom directives in AngularJS I was initially intimidated by the term “transclusion”. Just from hearing the word I could make no assumptions about its meaning and I was preparing myself to dig in and spend a significant amount of time learning and mastering a complex topic. To my complete surprise transclusion turned out to be a very simple topic that I learned in no time. For anyone new to AngularJS who has heard this term hopefully my explanation will prove useful.

Consider the following “Hello World” example:

app.js

var myApp = angular.module('myApp', []); myApp.directive('myDirective', function(){ return { restrict: 'E', transclude: true, template: '<div>' + '<p>Hello World!</p>' + '<ng-transclude></ng-transclude>' + '<p>Goodbye World!</p>' + '</div>' } });

index.html

<div ng-app="myApp"> <my-directive>My name is Ben</my-directive> </div>

Output:

Hello World! My name is Ben Goodbye World!

All that transclusion is doing is taking everything that you put between your opening and closing directive tag in your index.html and applying it to the appropriate location within your directive’s template.

To me this pattern was reminiscent of creating a function. The text/HTML that you put between your opening and closing directive tags is sort of like an argument that is then passed into your template “function”. That was how I initially conceptualized it.

On your directive definition object you need to add the property transclude and set it to true.

The text and markup that you want to transclude, or pass into the directive’s template, needs to be inserted within your directive’s opening and closing tag in your html file.

You reference this passed in text and markup by using the directive within your template.

Transclusion is a simple concept that is easy to implement and increases the power of what directives are capable of accomplishing. The above example is trivial but I hope that it can serve as a base upon which you can expand your understanding.

67 Kudos