您可以有条件地修改模板以在compile: 函数中包含ng-transclude。
.directive('foo', function () {
return {
restrict: 'E',
transclude: true,
replace: true,
templateUrl: 'foo.html',
compile: function (element, attrs) {
if (attrs.bar !== undefined) {
element.find('.may-transclude-here')
.attr('ng-transclude', '');
}
return function postLink(scope, element, attrs, controllers) {
scope.listEntries = ['apple', 'banana', 'tomato'];
};
}
}
})
和一个 html 模板:
<div class="foo">
<h4>Directive title</h4>
<div class="may-transclude-here" ng-repeat="item in listEntries">
Original content: {{item}}
</div>
<span>blah blah blah</span>
</div>
但是通过ng-transclude 嵌入的内容不会与ng-repeat 创建的每个项目的范围绑定。如果您还需要绑定,这里是 ng-transclude 的修改版本,它执行正确的范围绑定。
.directive('myTransclude', function () {
return {
restrict: 'EAC',
link: function(scope, element, attrs, controllers, transcludeFn) {
transcludeFn(scope, function(nodes) {
element.empty();
element.append(nodes);
});
}
};
});
Plunker 示例: http://plnkr.co/edit/8lncowJ7jdbN0DEowdxP?p=preview
希望这会有所帮助。