Search code examples
angularjsangularjs-ng-transclude

How do I access transclusion slots from the transclude function?


Angular 1.5 introduced multi-slot transclusion. According to the docs:

the transclude object { slotA: '?myCustomElement' } maps elements to the slotA slot, which can be accessed via the $transclude function

Unfortunately it doesn't give any examples of this. The only example it gives doesn't mention slots at all:

$transclude(function(clone, scope) {
  element.append(clone);
  transcludedContent = clone;
  transclusionScope = scope;
});

Can someone shed some light on how to access each slot using the $transclude function?


Solution

  • I had similar problem, but reading source code of ng-transclude helps. It turns out there is third argument to $transclude function, which is slot name.

    https://github.com/angular/angular.js/blob/master/src/ng/directive/ngTransclude.js#L190

    Simple example:

    angular.module('app', []);
    
    angular
      .module('app')
      .directive('dir', function () {
        return {
          transclude: {
            a: 'aT',
            b: 'bT'
          },
          link: function (scope, elem, attrs, ctrl, transclude) {
            transclude(function (content) {
              elem.append('<div>a</div>');
              elem.append(content);
            }, null, 'a');
            
            transclude(function (content) {
              elem.append('<div>b</div>');
              elem.append(content);
            }, null, 'b');
          }
        };
      });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.js"></script>
    
    <div ng-app="app">
      <dir>
        <a-t>content of a</a-t>
        <b-t>content of b</b-t>
      </dir>
    </div>