gpt4 book ai didi

angularjs - 何时在 Angular 中使用 transclude 'true' 和 transclude 'element'?

转载 作者:行者123 更新时间:2023-12-01 22:58:42 26 4
gpt4 key购买 nike

我应该什么时候使用 transclude: 'true'transclude: 'element' ?
我找不到关于 transclude: 'element' 的任何信息在 angular 文档中,它们非常令人困惑。

如果有人能用简单的语言解释这一点,我会很高兴。
每个选项的好处是什么?它们之间的真正区别是什么?

这是我发现的:

transclude: true

Inside a compile function, you can manipulate the DOM with the help of transclude linking function or you can insert the transcluded DOM into the template using ngTransclude directive on any HTML tag.





transclude: ‘element’

This transcludes the entire element and a transclude linking function is introduced in the compile function. You can not have access to scope here because the scope is not yet created. Compile function creates a link function for the directive which has access to scope and transcludeFn lets you touch the cloned element (which was transcluded) for DOM manipulation or make use of data bound to scope in it. For your information, this is used in ng-repeat and ng-switch.

最佳答案

来自 AngularJS Documentation on Directives :

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.



转置:真实

因此,假设您有一个名为 my-transclude-true 的指令。声明为 transclude: true看起来像这样:
<div>
<my-transclude-true>
<span>{{ something }}</span>
{{ otherThing }}
</my-transclude-true>
</div>

编译后和链接前变成:
<div>
<my-transclude-true>
<!-- transcluded -->
</my-transclude-true>
</div>

内容 my-transclude-true的( child )这是 <span>{{ something }}</span> {{... , 被嵌入并可供指令使用。

嵌入:'元素'

如果您有一个名为 my-transclude-element 的指令声明为 transclude: 'element'看起来像这样:
<div>
<my-transclude-element>
<span>{{ something }}</span>
{{ otherThing }}
</my-transclude-element>
</div>

编译后和链接前变成:
<div>
<!-- transcluded -->
</div>

在这里, 整个元素包括其子元素 被嵌入并提供给指令。

链接后会发生什么?

这取决于您的指令对 transclude 函数做它需要做的事情。 ngRepeat用途 transclude: 'element'这样它就可以在范围改变时重复整个元素及其子元素。但是,如果您只需要替换标签并希望保留其内容,则可以使用 transclude: truengTransclude为您执行此操作的指令。

关于angularjs - 何时在 Angular 中使用 transclude 'true' 和 transclude 'element'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18449743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com