我认为这是我用 angularjs 指令最难理解的概念之一。
来自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 文档中的示例根本不使用 ngTransinclude
指令。
我想要一些很好的例子来帮助我理解这一点。为什么我们需要它?它解决什么问题?如何使用?
最佳答案
考虑一个元素中名为 myDirective 的指令,并且该元素包含一些其他内容,比方说:
<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>
那么,如果您想保留 <button>...
该怎么办?和<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>.
总之,当您想在使用指令时保留元素的内容时,基本上可以使用 transclude。
关于angularjs - 了解指令定义的 transinclude 选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15296284/