AngularJS Transclusion with Example

Transclusion is called the inclusion of part or all of an electronic document into one or more other documents by hypertext reference.It is performed when the referencing document is displayed and is normally automatic and transparent to the end user. Transclusion gives a way to pass templates to directive and it is displayed. We will look at an example to see how the defining template inside the directive element reflects. Our directive is named myEmployee.

App.js


var app = angular.module('mainApp', []);

app.directive('myEmployee', function() {

  return {

      restrict: 'EA',

      scope:{}, //isolate scope.

     template: "<div>My First Directive.</div>"

  };

});


 we included an element inside the my-employee directive in the index.html file.

App.js


<!DOCTYPE html>

<html>

    <head lang="en">

      <meta charset="utf-8">

      <title>AngularJS Transclusion</title>

    </head>

    <body>

      <div ng-app="mainApp">

        <my-employee>

          <div>Transcluded Element. This will not be displayed Since the transclude property is not enabled. </div>

        </my-employee>

     </div>

</div>

      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>

      <script type="text/javascript" src="app.js"></script>

    </body>

</html>


You will TranscludeDisabled as the output. That is the content is not displayed. AngularJS provides a transclude property to support transclusion in directive. There are 2 key features. First one is a property that is used in directives named transclude and setting this to true enables the transclusion. Second feature is a directive named ng-transclude. It is used to define the place where you need to place the content in the directive’s template. Now we will see the modified example after including the key features.

App.js


var app = angular.module('mainApp', []);

app.directive('myEmployee', function() {

  return {

      restrict: 'EA',

      scope:{}, //isolate scope.

     transclude:true,

     template: "<div ng-transclude></div><div>My First Directive.</div>"

  };

});


Ng-transclude is a directive that marks the insertion point for transcluded DOM of the parent directive that uses the transclusion.

App.js

<!DOCTYPE html>

<html>

    <head lang="en">

      <meta charset="utf-8">

      <title>AngularJS Routing</title>


    </head>

    <body>


      <div ng-app="mainApp">

        <my-employee>

          <div>Transcluded Element. Transclude property is enabled.</div>

        </my-employee>

     </div>

</div>


      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>

      <script type="text/javascript" src="app.js"></script>

    </body>

</html>