The initial setup:
<body ng-app="greetings">
<welcome>
<button>Click this button</button>
</welcome>
</body>
angular.module('greetings', [])
.directive("welcome", function() {
return {
restrict: "E",
scope: {},
template: "<div>This is the welcome component</div>"
}
});
In this setup, the welcome element in the view will be evaluated to the element directive template, the div. The default for directives is to destructively replace the contents of the element meaning that the <button>
element will be removed entirely.
If the content within the panel element is intended to persist, the directive needs to have transclusion enabled:
return {
restrict: "E",
scope: {},
transclude: true,
template: "<div>This is the welcome component</div><ng-transclude></ng-transclude>"
}
With transclude enabled, anything that exists inside the welcome element in the view will be appended to the contents of whichever element in the template has the ng-transclude attribute. In this case, the "Click this button" button will be inserted directly following the text inside the view.
As a rule of thumb, transclusion should only be used on element directives, which should always specify a template and define an isolated scope. In this situation, the content that is transcluded will be attached to the parent scope NOT the isolated scope of the directive. This means that any Angular bindings in the transcluded directive will still reflect the values of the parent scope.