Episode 19 of 25
Transclude and Replace
Learn how transclude wraps content inside custom directives.
Transclude allows a custom directive to wrap content that is passed into it from the outside.
What is Transclude?
Think of it like a "content slot" — the directive defines the wrapper, and you provide the inner content:
app.directive('panelBox', function() {
return {
restrict: 'E',
transclude: true,
template: `
<div class="panel">
<div class="panel-header">My Panel</div>
<div class="panel-body" ng-transclude></div>
</div>
`
};
});
<!-- Usage -->
<panel-box>
<p>This content gets inserted into ng-transclude!</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</panel-box>
Result
<div class="panel">
<div class="panel-header">My Panel</div>
<div class="panel-body">
<p>This content gets inserted into ng-transclude!</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</div>
</div>
Transclude with Scope
app.directive('alertBox', function() {
return {
restrict: 'E',
transclude: true,
scope: {
type: '@'
},
template: `
<div class="alert alert-{{ type }}">
<strong>{{ type | uppercase }}:</strong>
<span ng-transclude></span>
</div>
`
};
});
<alert-box type="warning">Please save your work!</alert-box>
<alert-box type="success">File uploaded successfully.</alert-box>
Replace Option
The replace: true option replaces the directive element itself with the template:
app.directive('myHeader', function() {
return {
restrict: 'E',
replace: true, // replaces <my-header> with the template
template: '<header><h1>My Site</h1></header>'
};
});