visit
A
ngTransclude
directive is a thing I often found in many examples, yet I think it is not well explained in the official docs. I was never really sure how to use it, and I am sure I am not the only one. As I found, the general concept is not difficult, but documentation, which uses lots of big words, makes it hard to understand. I decided to create a quick user guide to describe how you can use ng-transclude
with a short but expository example.<div class="card">
<h1 class="header">{{header}}</h1>
<div class="content">{{content}}</div>
<button
type="submit"
class="button"
ng-click="buttonAction()">
{{buttonText}}
</button>
</div>
(function() {
'use strict';
angular
.module('app.card')
.directive('Card', Card);
function Card() {
return {
restrict: 'E',
replace: true,
scope: {
header: '@',
content: '@',
buttonAction: '&',
buttonText: '@'
},
templateUrl: 'card.html'
};
}
})();
It is very simple; data binding allows you to bind attributes values to this template. A
header
, content
and buttonText
are bound as text in the places where corresponding expressions occur. You can also pass a function to a button using buttonAction
. It can be done as simple as this:<card
header="Hello"
content="Do you want to continue?"
button-text="Nope"
button-action="$ctrl.close()">
</card>
<div class="card">
<h1 class="header">{{header}}</h1>
<div class="content" ng-transclude="cardContent"></div>
<button
type="submit"
class="button"
ng-click="buttonAction()">
{{buttonText}}
</button>
</div>
(function() {
'use strict';
angular
.module('app.card')
.directive('Card', Card);
function Card() {
return {
restrict: 'E',
replace: true,
transclude: {
cardContent: 'cardContent'
}
scope: {
header: '@',
buttonAction: '&',
buttonText: '@'
},
templateUrl: 'card.html'
};
}
})();
And now you can use it as you want. You can put whatever inside your directive html tag and it will be displayed inside a
div
with cardContent
transclusion. You can add a simple table inside:<card
header="Table"
button-text="Close"
button-action="$ctrl.close()">
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
</card>
<div class="card">
<h1 class="header">Table</h1>
<div class="content">
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
</div>
<button
type="submit"
class="button"
ng-click="$ctrl.close()">
Close
</button>
</div>
As you see values of every attributes are bound to selected elements and table was inserted to content
div
.This story was originally published on my Medium page on Nov 14, 2017 and had 1.4K views when moved to my Hackernoon page.