微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angularjs – 嵌套 – 被抄送的项目 – 范围澄清?

我已经知道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>

基本上我有一个控制器,< 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指令的代码

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

该计划始于:

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

该计划的输出是:

Hello,The value of “i” is => 1000

根据文档:myPane的transcluded数据应该可以访问指令的外部范围,该指令是myTabs指令,其值为i = 2.

但myPane具有独立的范围,因此它不会从myTabs继承范围.

那么它是否会更高一级到控制器的范围以获得i = 1000? (澄清,我不是问我怎样才能让我得到另一个价值 – 我问为什么/它如何具有1000的价值).

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

是这样的吗?

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

文档说:

The transclude option changes the way scopes are nested. It makes it
so that the contents of a transcluded directive have whatever scope is
outside the directive
,rather than whatever scope is on the inside. In
doing so,it gives the contents access to the outside scope.

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

换句话说,为什么/我如何= 1000?

FULL PLUNKER

在回答后编辑OP

安装和配置PeriScope后(来自@MarkRajcok)我现在可以直观地看到它:

enter image description here

解决方法

来自 $compile的文档

When you call a transclude function it returns a DOM fragment that is
pre-bound to a transclusion scope. This scope is special,in that it
is a child of the directive’s scope (and so gets destroyed when the
directive’s scope gets destroyed) but it inherits the properties of
the scope from which it was taken.

父层次结构(来自$$childTail)如下:

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

Prototypical Hierarchy就像(来自AngularJS Batarang的截图) –

ng-transclude proto hierarchy

更新了plunker,在控制台中打印了范围ID,可以为您提供更好的主意.

为什么这些不同,我不太确定.有人可以对此有所了解.

为什么值为1000.因为我需要作为双向属性提供=所以子范围可以修改它.我已经更新了上面的plunker,你现在可以看到值响应窗格控制器中的更改.

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐