Forward Advance Learning

Directive Transclusion

Transclusion allows you to take content that is already in the element and modify it in some way. Say you have a div like this:

<div my-directive>
World of Wonder
</div>

Now you apply a directive which includes a template.

.directive('myDirective', function() {
return {
template: "<div>World of Template</div>"
}
})

The innerHtml is set on the div and "World of Wonder" is no more. Sad. This is where transclusion comes in.

Transclusion allows us to access the element's original content which has been displaced by the template

When we tell a directive to transclude, the original content of the element is saved. Why would you want to do this?

Uses of transclusion

  • ng-if - the transcluded content is only visible when a condition is met.
  • ng-repeat - the transcluded content is repeated for each element of an array.
  • wrapping an element - for example, wrapping a row of buttons in a menu bar.

Scope of transcluded content

Transcluded content will have the $scope in which it was declared. If your directive has an isolate $scope, the transcluded content will not share it unless you explicitly compile against the isolate scope.

Consider carefully whether you need an isolate scope in this case.

The transclude directive

If we tell our directive to transclude, the content that was originally in the element will still be available to us via the transclude directive in our template, like so:

myApp.directive('transclusionDirective', function() {
return {
transclude:true,
template: "Here is the transcluded content: <span ng-transclude></span> Nice huh?"
}
});

Exercise - A transcluded header directive

Create a directive that will add a header and footer to any element. You can do this entirely using the a template and the ng-transclude directive.