从http://docs.angularjs.org/guide/directive的文件说:
transclude – compile the content of the element and make it available to the directive. Typically used with ngTransclude. The advantage of transclusion is that the linking function receives a transclusion function which is pre-bound to the correct scope. In a typical setup the widget creates an isolate scope,but the transclusion is not a child,but a sibling of the isolate scope. This makes it possible for the widget to have private state,and the transclusion to be bound to the parent (pre-isolate) scope.
- true – transclude the content of the directive.
- ‘element’ – transclude the whole element including any directives defined at lower priority.
它说transclude通常用于ngTransclude。但是从ngTransclude的文档的示例不使用ngTransclude指令。
我想要一些好的例子来帮助我理解这一点。为什么我们需要它?它解决什么?如何使用它?
<div my-directive> <button>some button</button> <a href="#">and a link</a> </div>
如果myDirective正在使用模板,您会看到< 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>
那么,如果你想在DOM中保留你的< button> …和< a href> …怎么办?你需要一种叫做互斥的东西。这个概念很简单:包含从一个地方到另一个地方的内容。所以现在你的指令看起来像这样:
app.directive('myDirective',function(){ return{ transclude: true,template: '<div class="something" ng-transclude> This is my directive content</div>' } });
这将呈现:
<div class="something"> This is my directive content <button>some button</button> <a href="#">and a link</a> </div>.
总之,你在使用指令时想要保留元素的内容时,基本上使用transclude。
我的代码示例是这里http://jsfiddle.net/7LRDS/1/
你也可以从观看:https://egghead.io/lessons/angularjs-transclusion-basics