javascript - 如何在递归模板中访问父对象

标签 javascript angularjs recursion

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

  • /
    • 图片/
      • 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 的父级?

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

最佳答案

如果您使用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/

相关文章:

javascript - promise 所有并获得请求

javascript - 您将如何获取 JSON 对象数组中所有子节点的 JSONPath?

javascript - 在 firefox 和 chrome 中上传图片

AngularJS:$cookies.remove不是一个函数

javascript - 尽管在 Controller 中使用数组语法,AngularJS 代码并未正确缩小

javascript - 同时循环遍历两个数组,并使用 Angular js [Angular 新手] 将每个数组的第一个元素一次传递给函数

javascript - Chrome 扩展仅在刷新时运行,而不是在页面导航时运行

python - Python 中的递归?运行时错误 : maximum recursion depth exceeded while calling a Python object

Javascript 修复我的 flatten(array) 函数

java - 减少递归子集求和算法的运行时间