假设我们有一个像这样的树结构:
- /
- 图片/
- foo.jpg
- 酒吧.jpg
- 天.jpg
- 视频/
- foo.mp4
- bar.mp4
- day.mp4
- 图片/
以及此结构在 JavaScript 对象中的表示:
$scope.tree = {
title: '/',
children: [{
title: 'images/',
children: [{
title: 'foo.jpg'
}, {
title: 'bar.jpg'
}, {
title: 'day.jpg'
}]
}, {
title: 'vids/',
children: [{
title: 'foo.mp4'
}, {
title: 'bar.mp4'
}, {
title: 'day.mp4'
}]
}]
};
可以通过使用 ng-include
递归渲染模板来渲染树:
<script type="text/ng-template" id="tree">
<a href="#" ng-click="logNodeAndParent(child, parent)">{{ child.title }}</a>
<ul>
<li ng-repeat="child in child.children" ng-include="'tree'" ng-init="parent=child">
</li>
</ul>
</script>
<ul>
<li ng-repeat="child in tree.children" ng-include="'tree'"></li>
</ul>
请注意,当您单击树中的一个节点时,我想记录子节点及其父节点:
$scope.logNodeAndParent = function(node, parent) {
console.log('Child: ' + node.title + ' Parent: ' + parent.title);
};
问题是,如何访问当前 child 的父级?
最佳答案
如果您使用ng-init
设置初始父级树
,那么在模板中,将parent 属性更新为$parent.$parent。 child
,它应该适用于所有级别。
<script type="text/ng-template" id="tree">
<a href="#" ng-click="logNodeAndParent(child, parent)">{{ child.title }}</a>
<ul>
<li ng-repeat="child in child.children" ng-include="'tree'" ng-init="parent = $parent.$parent.child">
</li>
</ul>
</script>
<ul>
<li ng-repeat="child in tree.children" ng-include="'tree'" ng-init="parent = tree"></li>
</ul>
这是一个更新的 fiddle :http://jsfiddle.net/NP7P5/5/
关于javascript - 如何在递归模板中访问父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23247707/