angularjsangularjs-directiveangularjs-ng-transclude

Using template from 1 directive into another directives template


Basically I have 2 custom directives, each having it's own template. What I need is to insert one of the templates into the other. I have also read about transclusion, but can't wrap my head around it. Any ideas would be of great help!


Solution

  • From the AngularJS Website, an example:

        <script>
      angular.module('transcludeExample', [])
       .directive('pane', function(){
          return {
            restrict: 'E',
            transclude: true,
            scope: { title:'@' },
            template: '<div style="border: 1px solid black;">' +
                        '<div style="background-color: gray">{{title}}</div>' +
                        '<ng-transclude></ng-transclude>' +
                      '</div>'
          };
      })
      .controller('ExampleController', ['$scope', function($scope) {
        $scope.title = 'Lorem Ipsum';
        $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
      }]);
    </script>
    <div ng-controller="ExampleController">
      <input ng-model="title" aria-label="title"> <br/>
      <textarea ng-model="text" aria-label="text"></textarea> <br/>
      <pane title="{{title}}"><span>{{text}}</span></pane>
    </div>
    

    You have to create the custom directive, in this case "pane", from inside angular.module. When you have done that, the directive exists from within the module which should be your application and you can use it freely as it is returned from the directive example. In this case the example uses the "pane" directive and it associates the transcluded template to it.