2014-05-15 130 views
0

有兩個指令collectionelement,它們都轉換它的內容,它們都有scope: false(默認值)。AngularJS:範圍不在嵌套的transcluded指令之間共享

該指令用於爲一些容器和包裝在該容器中的某些項目的包裝,並使用如下:

<body ng-app="myApp" ng-controller="MyController"> 
<collection> 
    <element>inner1</element> 
    <element>inner2</element> 
    <element>inner3</element> 
    </collection> 
</body> 

該指令被定義如下:

angular.module('myApp', []) 
.controller('MyController', function($scope){ 
    console.log('MyController', $scope.$id); 
}) 
.directive('collection', function($compile){ 
    return { 
     transclude: 'true', 
     restrict: 'E', 
     template: '<header>header</header><div><ul ng-transclude></ul></div><footer>footer</footer>', 
     link: function(scope){ 
      console.log('collection', scope.$id); 
     } 
    } 
}) 
.directive('element', function(){ 
    return { 
     restrict: 'E', 
     replace: true, 
     transclude: true, 
     template: '<li><div ng-transclude></div></li>', 
     link: function(scope){ 
      console.log('element', scope.$id); 
     } 
    } 
}); 

問題是指令element是使用不同的範圍作爲指令collection,我不明白爲什麼。

控制檯輸出

MyController 003 
element 004 
element 004 
element 004 
collection 003 

正如你所看到的,MyControllercollection同一範圍#3共享,但所有element -s使用範圍4#。

這裏是工作示例:plunkr

回答

2

當您登錄scope.$id在邏輯函數安慰,你登錄指令本身的範圍ID。但是,如果在指令中使用包含,則還會爲跨鏈接內容創建新範圍。

enter image description here

這是相當簡單的瞭解,一旦你看到它。一旦你set isolate scope on a directive using transclusion事情變得更有趣。