Recursively Display N-ary Tree
I'm trying to display an n-ary tree structure in the browser. Here's an example of the data structure it is being drawn from: var jsonObj = [{ id: 'window1', name: 'Corpor
Solution 1:
How about the following...
functioncreate_graph_components(json, level, offsetStart) {
var offsetEnd = offsetStart;
for (var i = 0; i < json.children.length; i++) {
offsetEnd = create_graph_components(json.children[i], level + 1, offsetEnd);
}
var offset;
if (json.children.length == 0) {
offset = offsetEnd;
// Node is a leaf therefore extend offsetEnd
offsetEnd += 50;
} else {
// Calculates position halfway between child nodes
offset = offsetStart + (offsetEnd - offsetStart - 50) / 2;
// Node is a branch therefore we do not extend the offsetEnd
}
// Create the elementvar child = $('<div id="' + json.id + '" class="component window">' +
'<strong>' + json.name + '</strong>' +
'</div>');
// Position the element
child.css({
top: offset + "px",
left: level * 150 + "px"
});
// Add it to the wrapper
$("#wrapper").append(child);
return offsetEnd;
}
I've created a fiddle too http://jsfiddle.net/j7Pms/
Solution 2:
I see your question is from 7 old, but if you need to refactor your code this is how to did it using an angular recursive template. I'll leave a snippet of the template in case you find it useful.
<table><ng-template #recursiveListlet-tree><divcdkDropList (cdkDropListDropped)="drop($event)"><div *ngFor="let node of tree; let i=index "cdkDrag><tr><app-default-node [node]="node"></app-default-node><td *ngIf="node.children!==null && node.children.length > 0"cdkDrag><ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: node.children }"></ng-container></td></tr></div></div></ng-template></table><ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: tree }"></ng-container>
Post a Comment for "Recursively Display N-ary Tree"