我在 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>'
};
});
输出标记
可视化:
关于angularjs - 什么是 ng-transinclude?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24725399/