2015-08-18 67 views
0

我想指出具有隔離範圍的指令。 在這個指令中有一些其他的指令,它們應該和它的父指令具有相同的範圍。使子範圍與父隔離範圍相同

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

我無法做到這一點。

編輯

this Plunker展示孩子們如何保持相同的範圍,因爲它的父父,如果是一個孩子的範圍。我忘了,當你不使用template/templateUrl時,元素內的數據不會被丟棄。

如果父母的範圍是孤立的,似乎孩子的範圍不能與父母範圍相同。需要將數據添加到父範圍。

+0

您需要手動跨屏。下面是我剛剛回答的一個問題:http://stackoverflow.com/a/32060662/968155 –

回答

0

您是否嘗試過在您的子指令定義對象上使用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); 
    } 
    }; 
}); 
+0

假設您不使用'ng-transclude',是不是有一種方法可以使父範圍與它的子範圍相同當父母有一個孤立的範圍?我做了一個更新的plunker,父母和孩子共享相同的範圍。但是我只能在沒有孤立範圍的情況下這樣做。 – gr3g

1

這是因爲ngTransclude。在文檔(https://docs.angularjs.org/guide/directive)中指出:

transclude選項更改了作用域嵌套的方式。它使它 ,以便transcluded指令的內容有任何範圍是指令外的 ,而不是內部的任何範圍。在 這樣做時,它將內容訪問到外部範圍。