angularjs - 什么是 ng-transinclude?

标签 angularjs angularjs-directive transclusion

我在 StackOverflow 上看到了很多讨论 ng-transclude 的问题,但没有一个问题能通俗地解释它是什么。

文档中的描述如下:

Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.

这相当令人困惑。有人能够用简单的术语解释 ng-transclude 的用途以及它可以在哪里使用吗?

最佳答案

Transclude 是一个设置,告诉 Angular 捕获标记中指令中放入的所有内容,并在某处使用它(实际上 ng-transclude 所在的位置)在指令的模板中。在 documentation of directives创建包装其他元素的指令部分中阅读有关此内容的更多信息。 .

如果您编写自定义指令,则可以在指令模板中使用 ng-transclude 来标记要插入元素内容的点

angular.module('app', [])
  .directive('hero', function () {
    return {
      restrict: 'E',
      transclude: true,
      scope: { name:'@' },
      template: '<div>' +
                  '<div>{{name}}</div><br>' +
                  '<div ng-transclude></div>' +
                '</div>'
    };
  });

如果您将其放入标记中

<hero name="superman">Stuff inside the custom directive</hero>

它会显示为:

Superman

Stuff inside the custom directive

完整示例:

Index.html

<body ng-app="myApp">
  <div class="AAA">
   <hero name="superman">Stuff inside the custom directive</hero>
</div>
</body>

jscript.js

angular.module('myApp', []).directive('hero', function () {
    return {
      restrict: 'E',
      transclude: true,
      scope: { name:'@' },
      template: '<div>' +
                  '<div>{{name}}</div><br>' +
                  '<div ng-transclude></div>' +
                '</div>'
    };
  });

输出标记

enter image description here

可视化:

enter image description here

关于angularjs - 什么是 ng-transinclude?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24725399/

相关文章:

angular - 动态插入 ng-content 选择

api - 如何从 ember 中的子组件范围访问父组件范围?

javascript - Howler.JS + Angular - 播放声音文件的路径

javascript - 带有数组的 AngularJS cookie

angularjs - 如何使兄弟指令通信工作(某些特定指令之间的通信)

javascript - AngularJS:如何处理路由 Controller 中的键盘快捷键?

javascript - AngularJS:过滤值更改时刷新 DOM

AngularJS - 通过 ng-click 传递 $index 或项目本身?

angularjs - 指令模板中的范围生成不适用于嵌入

string - YAML引用另一个文件中的另一个变量