-6ren">
gpt4 book ai didi

angularjs - 嵌套 - 嵌入项目 - 范围澄清?

转载 作者:行者123 更新时间:2023-12-04 15:55:51 24 4
gpt4 key购买 nike

我已经知道嵌入是如何工作的(我猜只是在第一级内),但是我对嵌套嵌入项的范围有疑问。

好的,所以我有这个代码:

<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>'
};
})

我知道指令的内容可以访问 指令的范围

所以黄色部分将可以访问外部范围(即主 Controller 范围):

enter image description here

这是 myPane 的代码指令:
  .directive('myPane', function()
{
return {
require: '^myTabs',
restrict: 'E',
transclude: true,
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's嵌入的数据应该可以访问指令的外部范围,即 myTabs值为 i=2 的指令.

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

问题

也是这样吗 更多 高于 Controller 的范围以获得 i=1000 ?? (澄清一下,我不是在问如何使 i 获得另一个值 - 我是在问为什么/如何它具有 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之外的作用域是什么?指令有?

换句话说, i=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)

原型(prototype)层次结构 就像(来自 AngularJS Batarang 的屏幕截图)-

ng-transclude proto hierarchy

更新 plunker在控制台中打印范围 id 应该会给你一个更好的主意。

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

为什么值为 1000。因为 需要以 的形式提供双向 属性 = 所以子作用域可以修改它。我已经更新了上面的 plunker,你现在可以看到值响应 pane 中的变化 Controller 。

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

关于angularjs - 嵌套 - 嵌入项目 - 范围澄清?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34162553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com