我在 Creating a Directive that Wraps Other Elements 上的 AngularJS 文档中阅读了有关 ng-transclude
的内容。我想我正确理解了它的作用。
如果您有一个指令应用于内部包含内容的元素,如下所示:
<my-directive>directive content</my-directive>
它将允许您使用 ng-transclude
标记指令模板中的元素,并且元素中包含的内容将在标记的元素内呈现。
如果 myDirective
的模板是
<div>before</div>
<div ng-transclude></div>
<div>after</div>
它将呈现为
<div>before</div>
<div ng-transclude>directive content</div>
<div>after</div>
<小时/>
我的问题是是否可以以某种方式将多个 html block 传递到我的指令中?
例如,假设指令用法如下所示:
<my-multipart-directive>
<part1>content1</part1>
<part2>content2</part2>
</my-multipart-directive>
并有一个类似的模板:
<div>
this: <div ng-transclude="part2"></div>
was after that: <div ng-transclude="part1"></div>
but now they are switched
<div>
我希望它呈现如下:
<div>
this: <div ng-transclude="part2">content2</div>
was after that: <div ng-transclude="part1">content1</div>
but now they are switched
<div>
也许我可以以某种方式将节点的 HTML 值绑定(bind)到模型,以便我能够以这种方式使用它,而无需将其称为“transclude”?
最佳答案
从 Angular 1.5 开始,现在可以创建多个插槽。您提供一个带有每个槽映射的对象,而不是transclude:true:
https://docs.angularjs.org/api/ng/directive/ngTransclude
angular.module('multiSlotTranscludeExample', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: {
'title': '?pane-title',
'body': 'pane-body',
'footer': '?pane-footer'
},
template: '<div style="border: 1px solid black;">' +
'<div class="title" ng-transclude="title">Fallback Title</div>' +
'<div ng-transclude="body"></div>' +
'<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
'</div>'
};
})
关于AngularJS : transcluding multiple sub elements in a single Angular directive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22079587/