如何使用 AngularJS 处理数据的递归渲染 [英] How to handle recursive rendering of data using AngularJS

查看:19
本文介绍了如何使用 AngularJS 处理数据的递归渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,其中包含一组具有递归关系的数据(树视图,使用递归).我尝试了几种通过 Angular 实现这一点的方法,但似乎没有一种方法能够呈现出可行的结果.

I have an application that has set of data that has a recursive relationship (a tree view, using recursion.) I've tried several ways to implement this via Angular, none of which seem to render a viable result.

这里的想法是我希望使用一组嵌套列表来呈现这些数据,从而允许多个 (7+) 级别的深度.为了简化事情(我的实际应用程序使用 Retangular),我构建了以下 plunker:

The idea here is that I wish to have this data rendered using a set of nested lists, allowing for numerous (7+) levels of depth. To simplify things (my actual application uses Restangular) I've built the following plunker:

http://plnkr.co/edit/dKT9OvpsMgnxmLwgF0ij

虽然顶级"数据正确呈现(只是第一个标题),但我使用嵌套控制器进行递归的尝试似乎失败了.这里的想法是树中的每个孩子"都使用它自己的控制器渲染,然后控制器可以渲染它的孩子,等等.我意识到嵌套控制器可能不是最佳"的方式,但经过多次搜索后,我还没有找到更好"的替代方案.

While the "top" level data renders correctly (just the first title) my attempt to recurse using nested controllers seems to fail miserably. The idea here is that each "child" in the tree is rendered using it's own controller, which can then render it's children, and so-on and so-forth. I realize that nested controllers might not be the "best" way to go, but after much searching I haven't found a "better" alternative.

重要的是,最终的解决方案在这里保留了嵌套"的概念(每个元素都出现在其父元素下方,并带有轻微的缩进.)

It's important that the resulting solution preserves the concept of "nesting" here (each element appearing below its parent element, with a slight indent.)

推荐答案

与其嵌套控制器,不如嵌套数据并拥有一个控制器.

rather than nest your controllers, nest the data and just have the one controller.

视图由递归引用自身的模板处理.

the view is handled by a template that references itself recursively.

正如 chadermani 所说,这里有一些答案.

as chadermani has linked to, there are some answers out there.

这是一个很好的例子(不是我的代码)

here is a fiddle with a great example (not my code)

http://jsfiddle.net/brendanowen/uXbn6/8/

以及来自小提琴的代码

<script type="text/ng-template"  id="tree_item_renderer.html">
    {{data.name}}
    <button ng-click="add(data)">Add node</button>
    <button ng-click="delete(data)" ng-show="data.nodes.length > 0">Delete nodes</button>
    <ul>
        <li ng-repeat="data in data.nodes" ng-include="'tree_item_renderer.html'"></li>
    </ul>
</script>

<ul ng-app="Application" ng-controller="TreeController">
    <li ng-repeat="data in tree" ng-include="'tree_item_renderer.html'"></li>
</ul>

angular.module("myApp", []).
controller("TreeController", ['$scope', function($scope) {
    $scope.delete = function(data) {
        data.nodes = [];
    };
    $scope.add = function(data) {
        var post = data.nodes.length + 1;
        var newName = data.name + '-' + post;
        data.nodes.push({name: newName,nodes: []});
    };
    $scope.tree = [{name: "Node", nodes: []}];
}]);

这篇关于如何使用 AngularJS 处理数据的递归渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆