Search code examples
angularjstransclusion

How to transclude anything


I am transcluding an SVG element into another SVG directive. Here is the template for the parent directive called "component":

<svg xmlns="http://www.w3.org/2000/svg">

   <rect class="component-rect" width="{{rectWidth}}" height="{{rectHeight}}"></rect>

   <g ng-transclude></g>

</svg>

and here is the markup where the directive is used:

<g>
    <component ng-repeat="(id, component) in placedComponents">
        <text>{{component.label}}</text>
    </component>
</g>

I want to resize the <rect> in the template according to measured size of the transcluded <text> element. How can I get a reference to the transcluded <text> element in order to measure it and set the appropriate rectWidth and rectHeight?


Solution

  • You could remove the ng-transclude in the template, and do the trascultion yourself in the link function like this:

    .directive('component', function () {
      return {
        restrict: 'E',
        templateUrl: 'component.html',
        transclude: true,
        link: function (scope, element, attrs, ctrls, transcludeFn) {
          scope.rectHeight = 100;
          scope.rectWidth = 100;
    
          transcludeFn(function (clones) {
            // clones are the transcluded elements
            element.find('g').append(clones);
          });
        }
      }
    });
    

    Example plunker: http://plnkr.co/edit/Zv9Q6AuNGfzeN2gs7q2f?p=preview

    Hope this helps.