Directive transclusion

Transclusion on its own is a relatively simple construct in AngularJS. This simplicity becomes muddied when mixed with the complexity of directives and scope inheritance. Directive transclusion is frequently used when the directive either needs to inherit from the parent scope, manage nested HTML, or both.

How to do it…

Assemble all the pieces required to use transclusion. This is shown here:

(index.html - uncompiled)

<div ng-app="myApp">
  <div ng-controller="MainCtrl">
    <my-directive>
      <p>HTML template</p>
      <p>Scope from {{origin}}</p>
      <p>Overwritten? {{overwrite}}</p>
    </my-directive>
  </div>
  
  <script type="text/ng-template" id="my-directive.html">
    <ng-transclude></ng-transclude> </script> </div> (app.js) angular.module('myApp', ...

Get AngularJS Web Application Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.