【问题标题】:AngularJS : Bind to transclusive directive without isolating the scopeAngularJS:绑定到transclusive指令而不隔离范围
【发布时间】:2014-07-30 08:59:21
【问题描述】:

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

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

自定义指令是否可以使用 bindTo 属性进行绑定,允许被转入的内容访问属性,而不隔离自定义的范围?基本上,我希望一个指令绑定到模型的自定义部分,而不会将其从其父级的范围中切断,也不必添加额外的代码,例如:

scope.prop = scope.$parent.prop;

有什么想法吗?

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

【问题讨论】:

  • 我认为你不能在不污染包装范围的情况下做到这一点(例如使用bindTo)。如果你污染了包装范围,那么如果页面上有超过 1 个custom 指令,它就会中断。
  • @ExpertSystem 我认为如果他们使用 scope:true 并将该范围作为第一个参数传递给 transclude 函数(查看我的答案),他们应该能够做到这一点
  • @MarcKline:是的,我的意思是他们不能共享范围。只要原型继承不妨碍您,您的方法就很好(例如,您不需要从嵌入元素更新原始值)。但除此之外,它确实有效。
  • @ExpertSystem 谢谢。是的,这就是为什么我包括关于确保它们在模型中具有点的注释(例如它们不是原语)

标签: javascript angularjs data-binding angularjs-directive angularjs-scope


【解决方案1】:

通过使用scope: true,您可以通过原型继承保持对父作用域属性的访问,同时为指令的每个实例保持唯一作用域(即,使其可重用)。 (注意:确保您遵守 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

【讨论】:

  • 请注意,根据文档,compiletransclude is deprecated,因此您应该使用linktransclude
  • 没见过。我刚刚更新了我的答案和演示以反映这一点。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-07
  • 2015-12-08
  • 1970-01-01
相关资源
最近更新 更多