2015-12-08 62 views
6

我已经知道transclusion是如何工作的(仅在第一级我猜),但我有一个关于嵌套transcluded项目的范围的问题。嵌套 - 透明物品 - 范围澄清?

好了,所以我有这样的代码:

<body ng-app="docsTabsExample" ng-controller="ctrl"> 
    <my-tabs> 
    <my-pane title="Hello"> 
     <h4>Hello , The value of "i" is => {{i}}</h4> 
    </my-pane> 
    </my-tabs> 
</body> 

基本上我有一个controller<my-tabs><my-pane >。在myTabs指令

展望:

.directive('myTabs', function() 
    { 
     return { 
      restrict: 'E', 
      transclude: true, 
      scope: 
      {}, 
      controller: ['$scope', function($scope) 
      { 
       $scope.i = 2; 
      }], 
      template: '<div ng-transclude></div>' 
     }; 
    }) 

我知道指令的内容将有机会获得指令的范围

所以黄色部分将有机会获得外范围(这是主控制器范围):

enter image description here

这里是myPane指令代码:

.controller('ctrl', function($scope) 
{ 
    $scope.i = 1000; 
}) 

程序的输出是:

.directive('myPane', function() 
    { 
     return { 
      require: '^myTabs', 
      restrict: 'E', 
      transclude: true, 
      scope: 
      { 
      }, 
      controller: function($scope) 
      { 
       $scope.i = 4; //different value 
      }, 
      template: '<div ng-transclude></div>' 
     }; 
    }) 

该程序将启动

你好,的“我的价值“is => 1000

根据文档:myPane's transcluded数据应该可以访问哪些是myTabs指令,它的值为i=2指令的外部范围。

myPane孤立范围,以便它继承myTabs范围。

问题

所以它再涨到控制器的范围多个等级为了得到i=1000(澄清,我不问我怎么能让i获得另一个价值 - 我问为什么/如何具有1000的价值)。

我的意思是范围层次结构在这里看起来如何?

这是这样吗?

  controller's scope 
       | 
     +--------+---------+ 
     |     | 
    myTabs's    mypanes's 
transcluded   transcluded 
data's scope   data's scope   

的文档说:

的transclude选项更改范围嵌套的方式。它使得它 ,以便transcluded指令的内容有,无论范围是 指令以外,而不是内部的任何范围。在 这样做时,它将内容访问到外部范围。

myPAne指令的外部有什么范围?

换句话说,为什么/ 如何确实i=1000

FULL PLUNKER

编辑从OP的答案后

安装和配置潜望镜(从@MarkRajcok)后,现在我可以看到它在视觉上:

enter image description here

+2

两个MYTAB和myPane有'transclude:TRUE'。 myPane嵌套在myTab中。你给myPane myTab的范围,然后myTab是ctrl的范围,这给了myPane ctrl的范围。 – jperezov

回答

1

从上Docs $compile

当您调用transclude函数时,它将返回一个预先绑定到一个包含范围的 的DOM片段。这个范围是特殊的,因为它是 是指令作用域的子节点(因此当 指令的作用域被销毁时会被销毁),但它继承了从中获取它的范围 的属性。

层次(从$$ childTail)是这样的:

-1 (root) 
--2 (ctrl) 
---3 mytab 
----4 ($$transcluded = true) 
------5 mypane 
--------6 ($$transcluded = true) 

原型层次是像(截图从AngularJS Batarang) -

ng-transclude proto hierarchy

更新plunker与范围编号打印在控制台应该给你一个赌注这个想法。

为什么这些不同,我不是很确定。有人可以对此发出光芒。

为什么值为1000。其因需要为双向属性=提供这样子作用域可以对其进行修改。我已经更新了上面的调度器,你可以看到现在的值响应在pane控制器中的变化。

更多关于transcluded范围 -
Confused about Angularjs transcluded and isolate scopes & bindings
https://github.com/angular/angular.js/wiki/Understanding-Scopes

+0

为什么你把我添加到隔离范围?我的问题没有。另外 - 在你的运动员 - 你能解释什么是“mypane父母4”?我知道mytabs和mypane都有单独的(不同的)范围。但什么是“mypane父母4”?什么是mypane的父母? –

+0

Transcluded范围是一个特殊的范围。在上面的情况中,“mypane parent 4”是transcluded范围。我已经用一个解释transcluded作用域的链接更新了这篇文章。 –

+0

但是我的问题有两个横贯的项目,所以为什么我只看到第四个? –