If you know ui-router, multi-transclude should be easy for you also. In previou Angular version <1.4, one diretive can only have one transclude element. But now in Angular 1.5, you can give each transclude element a name, then you can have multi-transcluded elements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="node_modules/angular/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="app">
<ng-details>
<detail-title>Details</detail-title>
<detail-content-text >This is text content</detail-content-text>
</ng-details>
</body>
</html>
var app = angular.module('app', []); app.directive('ngDetails', function () {
return {
restrict: 'E',
scope: {},
transclude: {
'title': 'detailTitle', // title: used in directive template, detailTitle: used in app html
'textContent': 'detailContentText'
},
controller: function(){
this.toggle = true;
this.toggleIt = function(){
this.toggle = !this.toggle;
}
},
controllerAs: 'vm',
template: [
'<div class="details">',
'<div class="summary" ng-click="open = !open">',
'{{ open ? \'▾\' : \'▸\' }}',
'<span ng-transclude="title">default title</span>',
'</div>',
'<div class="content" ng-if="vm.toggle" ng-show="open" ng-transclude="textContent">default text</div>',
'</div>'
].join('')
};
});
This can make html code lot more easy to follow.
Another benefit is we can choose which element to be transcluded into our template:
<ng-details>
<detail-title>Details</detail-title>
<detail-content-text >This is text content</detail-content-text>
<detail-content-image >Sorry there is no image</detail-content-image>
</ng-details>
In app html, we add one more transclude element: detail-content-image, but it is not yet showing on the page.
var app = angular.module('app', []); app.directive('ngDetails', function () {
return {
restrict: 'E',
scope: {},
transclude: {
'title': 'detailTitle',
'textContent': 'detailContentText',
'imageContent': 'detailContentImage',
},
controller: function(){
this.toggle = true;
this.toggleIt = function(){
this.toggle = !this.toggle;
}
},
controllerAs: 'vm',
template: [
'<div class="details">',
'<div class="summary" ng-click="open = !open">',
'{{ open ? \'▾\' : \'▸\' }}',
'<span ng-transclude="title">default title</span>',
'</div>',
'<div class="content" ng-if="vm.toggle" ng-show="open" ng-transclude="textContent">default text</div>',
'<div class="content" ng-if="!vm.toggle" ng-show="open" ng-transclude="imageContent">default image</div>',
'</div>',
'<button ng-click="vm.toggleIt()">Toggle it: {{vm.toggle}}</button>'
].join('')
};
});
So, based on the toggle button, the template can choose which element to transclude into the template.
---------------------------------
Component refactor: