gpt4 book ai didi

javascript - Angular : Bind to transclusive directive without isolating the scope

转载 作者:行者123 更新时间:2023-11-30 17:26:34 25 4
gpt4 key购买 nike

假设我有一些 Angular 标记,例如:

<custom bindTo="modelProperty">
<!-- Trascluded content. -->
</custom>

自定义指令是否可以使用 bindTo 属性进行绑定(bind),从而允许嵌入的内容可以访问属性,而无需隔离自定义范围?基本上,我想要一个指令绑定(bind)到模型的自定义部分,而不会将其从其父级范围中分离出来,也不必添加额外的代码,例如:

scope.prop = scope.$parent.prop;

有什么想法吗?

编辑我想它的结构类似于 http://plnkr.co/edit/zq2OO1?p=preview ,除了工作和没有隔离范围。

最佳答案

通过使用 scope: true,您可以通过原型(prototype)继承保持对父范围属性的访问,同时为指令的每个实例保持唯一范围(即,以便它可重用)。 (注意:确保您观察到 the dot rule 以了解您需要从嵌入的内容中在父范围上更改的任何模型)

您需要从 compile 函数调用 transclude 函数,将指令的范围作为第一个参数传递,以便将嵌入的内容链接到它。

它可能看起来像这样:

.directive('custom', function() {
return {
restrict: 'E',
transclude: true,
scope: true,
link: function(scope, elem, attrs, ctrl, transclude){
scope.bindTo = scope[attrs.bindTo];
transclude(scope, function(clone){
elem.find('ng-transclude').replaceWith(clone);
});
},
template: '<div>From parent scope: <i>{{someVar}}</i> <ng-transclude></ng-transclude></div>'
}
});

Demo

关于javascript - Angular : Bind to transclusive directive without isolating the scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24126736/

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