如何从透传函数访问透传槽



Angular 1.5引入了多槽透入。根据文档:

对象{slotA: '?myCustomElement'}将元素映射到slotA插槽,可以通过$transclude函数

访问该插槽。

不幸的是,它没有给出任何这样的例子。它给出的唯一一个例子根本没有提到槽:

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

有人能说明如何使用$ translude函数访问每个插槽吗?

我有类似的问题,但阅读源代码ng-transclude帮助。原来$ translude函数还有第三个参数,那就是槽名。

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

简单的例子:

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>

最新更新