考虑一个名为我的指令在一个元素中,并且该元素包含一些其他内容,比方说:
<div my-directive>
<button>some button</button>
<a href="#">and a link</a>
</div>
If 我的指令正在使用模板,你会看到的内容<div my-directive>
将被您的指令模板替换。所以有:
app.directive('myDirective', function(){
return{
template: '<div class="something"> This is my directive content</div>'
}
});
将导致这样的渲染:
<div class="something"> This is my directive content</div>
请注意,原始元素的内容<div my-directive>
会迷路(或者更好地说,被替换)。那么,跟这些朋友说再见吧:
<button>some button</button>
<a href="#">and a link</a>
那么,如果您想保留自己的<button>...
and <a href>...
在 DOM 中?你需要一种叫做嵌入的东西。这个概念非常简单:将一处的内容包含到另一处。所以现在你的指令看起来像这样:
app.directive('myDirective', function(){
return{
transclude: true,
template: '<div class="something"> This is my directive content</div> <ng-transclude></ng-transclude>'
}
});
这将呈现:
<div class="something"> This is my directive content
<button>some button</button>
<a href="#">and a link</a>
</div>.
总之,当您在使用指令时想要保留元素的内容时,基本上可以使用 transinclude。
我的代码示例是here http://jsfiddle.net/7LRDS/1/。
您还可以从观看中受益this https://egghead.io/lessons/angularjs-transclusion-basics.