(#3) Transclusion in angularjs

Transclusion is one of the those topics which was quite difficult for me to understand at first. It was when I dicided to write this article that I fully understood the concept of transclusion. If we mention transclusion: true in the directive defination then it will make sure that the original content of the directive is available to use and attach to some other portion of the template.

In link function the fifth element is the transclusion (first four being the element, scope, the attributes and the required controllers).

So let me explain to you in code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//defination of directive
app.directive('myCard', function(){
return{
restrict: 'AE',
transclude: true,
templateUrl: 'template.html',
link: function(scope, elem, attrs, ctrls, transclude){
el.find('.content').append(transclude()); // this would tell transclude the elements inside directive (inject) into resulting html where the class is 'content'.
}
}
})
// pre-compiled html code
<my-card my-title="basic">
<p>viva la vida</p>
<h1>working awesome</h1>
</my-card>
// template.html
<article>
<h2>{{title}}</h2>
<div class="content">
</div>
</article>
// resulting html page
<my-card my-title="basic">
<article>
<h2>{{title}}</h2>
<div class="content">
<p>viva la vida</p>
<h1>working awesome</h1>
</div>
</article>
</my-card>

For working example please click here

Transclusion helps in injecting pre-compiled content of a directive to a post-compile directive with or without modifiying the actual content.