AngularJS:绑定到transclusive指令而不隔离范围

时间:2014-06-09 18:41:32

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

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

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

自定义指令是否可以使用bindTo属性进行绑定,允许转换内容可以访问属性,而不会隔离自定义的范围?基本上,我想要一个指令绑定到模型的自定义部分,而不必将其从父节点的范围中删除,而无需添加额外的代码,如:

scope.prop = scope.$parent.prop;

有什么想法吗?

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

1 个答案:

答案 0 :(得分:2)

通过使用scope: true,您可以通过原型继承维护对父作用域属性的访问,同时为指令的每个实例维护唯一作用域(即,使其可重用)。 (注意:请确保在翻译内容中针对父作用域需要更改的任何模型观察the dot rule

您需要从transclude函数调用compile函数,将指令的范围作为第一个参数传递,以便将已转换的内容与其相关联。

它可能看起来像这样:

.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