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>
它会显示为:
超人
自定义指令中的内容
完整示例:
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>'
};
});
Output markup
可视化: