AngularJS:嵌套的transcluded指令之间不共享范围

时间:2014-05-15 14:55:09

标签: javascript angularjs angularjs-directive angularjs-scope

有两个指令collectionelement,它们都转换了它的内容,它们都有scope: false(默认值)。

此指令用作该容器中某些项目的某个容器和包装器的包装器,并按如下方式使用:

<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

1 个答案:

答案 0 :(得分:2)

在链接函数中将scope.$id记录到控制台时,您将记录指令本身的范围ID。但是,在指令中使用transclusion时,还会为已转换的内容创建新范围。

enter image description here

一旦你看到它,这很容易理解。一旦你set isolate scope on a directive using transclusion,事情会变得有趣。