在命名透传槽中,如何“仅”透传元素的内容?

In a named transclude slot, how do I transclude *only* the element's contents?

本文关键字:元素 如何      更新时间:2023-09-26

我有一个基本的指令,我想使用透传。相关选项设置如下:

restrict: "E",
replace: true,
transclude: {
  'toolbar': 'toolbarSlot'
},
scope: {
  pageTitle: "@"
},
templateUrl: "path/to/my/template.html"

我的模板是:

<header class="page-header">
  <h1 class="page-title heading">{{ pageTitle }}</h1>
  <div class="page-header-toolbar toolbar" ng-transclude="toolbar">
    <!-- "toolbar" transcluded content should go here -->
  </div>
</header>

最后,当我使用指令时,我是这样使用的:

<my-custom-page-header-directive page-title="Title">
  <toolbar-slot>
    <button>Button</button>
    <button>Another button</button>
  </toolbar-slot>
</my-custom-page-header-directive>

问题是,在DOM中,它最终是这样的,一个无关的toolbar-slot元素混入了被包含的内容:

<header class="page-header">
  <h1 class="page-title heading">Title</h1>
  <div class="page-header-toolbar toolbar">
    <toolbar-slot>
      <button>Button</button>
      <button>Another button</button>
    </toolbar-slot>
  </div>
</header>

是否有一种方法(使用ngTransclude)仅跨出槽元素的内容 ?

看起来答案是不,目前还没有办法做到这一点

在Angular.js存储库中有一个公开的问题表明,对于以这种方式实现使用ngTransclude的能力存在疑虑:

我不赞成在槽传递中添加替换功能。它将引入与我们使用普通"replace"和transclude: element相同的问题。

但是,显然,"如果你真的需要的话,你可以手动完成"。