如何访问递归模板中的父对象



假设我们有这样的树结构:

  • /
    • 图像/
      • foo.jpg
      • bar.jpg
      • 天.jpg
    • 视频/
      • foo.mp4
      • 巴.mp4
      • 第.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);        
};

问题是,我如何访问当前子项的父项?

http://jsfiddle.net/benfosterdev/NP7P5/2/

如果使用ng-init设置初始父级tree,然后在模板中将父级属性更新为$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>

这是一个更新的小提琴:http://jsfiddle.net/NP7P5/5/

使用$parent$parent.child而不是parent。

<a href="#" ng-click="logNodeAndParent(child, $parent.$parent.child)">{{ child.title }}</a>

看看这个plunkrout:

http://jsfiddle.net/L6Vqn/6/

我相信这是因为ng repeat创建了一个新的作用域,然后ng include创建了另一个新作用域,因此您必须使用$parent两次。

最新更新