【问题标题】:Make child scope same as parent isolated scope使子范围与父隔离范围相同
【发布时间】:2015-08-18 23:26:06
【问题描述】:

我想创建一个具有隔离范围的指令。 在这个指令中还有一些其他指令,它们应该与它的父级具有相同的范围。

<parent> <!-- Isolated scope --> 
  <child> </child> <!-- Belongs to the container isolated scope -->
</parent>

我无法做到这一点。

编辑

this Plunker 展示了如果 parent 是子范围,则子级如何保持与其父级相同的范围。我忘了,当你不使用模板/模板Url时,元素内的数据不会被丢弃。

如果父范围是孤立的,似乎子范围不能与父范围相同。需要将数据添加到父范围。

【问题讨论】:

标签: angularjs


【解决方案1】:

这是因为 ngTransclude。在文档 (https://docs.angularjs.org/guide/directive) 中指出:

transclude 选项改变了范围嵌套的方式。它使它 以便嵌入指令的内容具有任何范围 在指令之外,而不是内部的任何范围。在 这样做,它使内容可以访问外部范围。

【讨论】:

    【解决方案2】:

    您是否尝试过在您的子指令定义对象上使用require 属性?您需要在父级上定义一个控制器,并在子指令中将require 属性设置为^container,然后您将可以在link 函数中作为第四个参数访问父级控制器:

    angular.module('app', [])
    
    .directive('container', function(){
      return {
    
        restrict : 'E',
    
        transclude : true,
    
        scope : {
    
        },
    
        template : 'container <ng-transclude> </ng-transclude>',
    
        controller: function($scope){
            // use this to add properties to the controller itself
            // which you can then access in the child directive
            this.container  = "container";
        },
    
        link : function($scope){
    
        } 
      };
    })
    
    .directive('child', function(){
      return {
        require: '^container',
        restrict : 'E',
        template : 'child container',
    
        link : function($scope, element, attrs, containerController){
          $scope.child  = "child";
    
          // logs: containerController Object {container: "container"}
          console.log('containerController', containerController); 
        }
      };
    });
    

    【讨论】:

    • 假设您不使用ng-transclude,当父级具有独立范围时,是否有办法使父级范围与子级相同?我做了一个更新的 plunker,其中父级和孩子共享相同的范围。但我只能在他们没有孤立的范围时才能这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多