我最近在指令中遇到了包含,有这个概念的目的是什么。据我所知,它封装了一个对象并且可能具有双向绑定(bind)。但这可以通过在指令的范围属性中使用“=”来实现。那么指令有什么大不了的呢?
最佳答案
嵌入允许:
- 创建包装其他元素的指令。
- 多次克隆相同的嵌入内容。
- 在事件发生时重新克隆被嵌入的内容。
ngTransclude 和 $transclude
- 使用transclude 选项时,元素内容会在编译阶段从 DOM 中删除。
linking phase
(or $transclude inside directive controllers)的第 5 个参数是一个$transclude 函数
,它允许你克隆嵌入的内容,将其应用于范围并在需要时将其重新插入 DOM。- Angular.js 有一个针对简单情况的内置指令:ngTransclude
我推荐这些教程:
一些 Angular 内置指令(ng 模块)使用transclude
选项:
在docs
What does transclude option do? it makes the contents of a directive with this option have access to the scope outside of the directive rather than inside.
实际上,这不太准确,它仅适用于 angular.js 内置指令的默认行为和 $transclude 函数在没有范围参数的情况下调用时的默认行为。
$transclude 函数允许您应用任何您需要的范围作为可选的第一个参数:
app.directive('example',function(){
return {
transclude: true,
template: "<div>example</div>"
link: function (scope, element, attrs, ctrl, $transclude){
$transclude(scope, function(clone){
element.append(clone);
})
}
}
})
关于angularjs - angularjs中包含的主要用途是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21087717/