问题描述
我已经设置了一个递归关系数据的应用(一树视图,使用递归)。我试过几种方式通过角,其中没有实现这个似乎呈现一个可行的结果。
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+)的深度水平。为了简化事情(我的实际应用程序使用Restangular)我已经构建了以下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:
虽然顶级数据正确呈现(只是第一个冠军),我尝试使用嵌套控制器递归似乎惨败。这里的想法是,每一个子在树中使用渲染它自己的控制器,那么它可以呈现它的孩子,等等上,因此来回。我认识到嵌套的控制器可能不是最好的路要走,但经过一番搜索我还没有发现一个更好的选择。
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.
重要的是,得到的溶液preserves的嵌套在这里的概念(出现它的父元素的下面每一个元素,有轻微的凹痕。)
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.
在这里是一个很好的例子(不是我的code)
here is a fiddle with a great example (not my code)
和从小提琴的code
and the code from the fiddle
<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数据递归渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!