ng-repeat
为每个元素创建一个新的范围。
ng-include
还创建了一个新的范围。
当你使用ng-include
和...一起ng-repeat
,为每个元素创建 2 个范围:
- 范围创建者
ng-repeat
对于当前元素。该范围保存迭代中的当前元素。
-
子范围由...制作
ng-include
which inherits from ng-repeat
的创建范围。
The $parent
当前作用域的属性允许您访问其父作用域。
本质上,范围创建者ng-include
是空的,当你访问value
and key
在你的node.html
,它实际上访问的是继承的价值观来自创建的父范围ng-repeat
.
在你的node.html中,访问{{value}}
实际上是一样的{{$parent.value}}
。因此,如果您需要访问当前元素的父元素,则必须通过访问来更进一步{{$parent.$parent.value}}
This DEMO http://jsfiddle.net/dqrb5/1/会澄清事情:
<script type="text/ng-template" id="node.html">
<div>
Current: key = {{key}}, value = {{value}}
</div>
<div>
Current (using $parent): key = {{$parent.key}}, value = {{$parent.value}}
</div>
<div>
Parent: key = {{$parent.$parent.key}}, value = {{$parent.$parent.value}}, isArray: {{isArray($parent.$parent.value)}}
</div>
<ul ng-if="isObject(value)"> //only iterate over object to avoid problems when iterating a string
<li ng-repeat="(key,value) in value" ng-include="'node.html'"></li>
</ul>
</script>
如果您需要简化访问父级的方式,您可以尝试使用初始化父级onload
of ng-include
。像这样:
在你的顶层,没有ng-if
=> 只有 2 层深
<ul>
<li ng-repeat="(key,value) in json"
ng-include="'node.html'" onload="parent=$parent.$parent"></li>
</ul>
在你的子级别中,有ng-if
=> 3 层深:
<ul ng-if="isObject(value)">
<li ng-repeat="(key,value) in value"
ng-include="'node.html'" onload="parent=$parent.$parent.$parent"></li>
</ul>
在模板内部,您可以使用以下方式访问父级:parent
,祖父母使用parent.parent
等等。
DEMO http://jsfiddle.net/C6E3k/1/