Understanding the transclude option of directive definition?

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

<div my-directive>
    <button>some button</button>
    <a href="#">and a link</a>
</div>

If myDirective is using a template, you’ll see that the content of <div my-directive> will be replaced by your directive template. So having:

app.directive('myDirective', function(){
    return{
        template: '<div class="something"> This is my directive content</div>'
    }
});

will result in this render:

<div class="something"> This is my directive content</div> 

Notice that the content of your original element <div my-directive> will be lost (or better said, replaced). So, say good-bye to these buddies:

<button>some button</button>
<a href="#">and a link</a>

So, what if you want to keep your <button>... and <a href>... in the DOM? You’ll need something called transclusion. The concept is pretty simple: Include the content from one place into another. So now your directive will look something like this:

app.directive('myDirective', function(){
    return{
        transclude: true,
        template: '<div class="something"> This is my directive content</div> <ng-transclude></ng-transclude>'
    }
});

This would render:

<div class="something"> This is my directive content
    <button>some button</button>
    <a href="#">and a link</a>
</div>. 

In conclusion, you basically use transclude when you want to preserve the contents of an element when you’re using a directive.

My code example is here.
You could also benefit from watching this.

Leave a Comment