Consider a JSON tree structure like the one shown below:
var myTree = {
"node": {
"name": "A",
},
"children": [
{
"node": {
"name": "B",
},
"children": []
},
{
"node": {
"name": "C",
},
"children": []
}
]
}
This example represents the basic structure of a tree, which can be much larger and have an unknown depth in real scenarios.
The goal is to display this tree in an AngularJS app using nested <ul>
elements as shown below:
<ul>
<li>A
<ul>
<li>B</li>
<li>C</li>
</ul>
</li>
</ul>
The focus is on achieving the nested bullet point display rather than exact formatting.
To convert the JSON tree to the desired HTML structure, a recursive function is implemented as follows:
self.HTMLTree = function(jsonTree) {
var retStr = '<li>' + jsonTree.node.name;
if (('children' in jsonTree) && (jsonTree.children.length > 0)) {
retStr += '<ul>';
for (childIndex = 0; childIndex <= jsonTree.children.length - 1; childIndex++)
retStr += self.HTMLTree(jsonTree.children[childIndex]);
retStr += '</ul>';
}
retStr += '</li>';
return retStr
}
Invocation in the HTML template is done like this:
{{myCtrl.HTMLTree(myCtrl.myTree)}}
When the page is loaded, the HTML returned by HTMLTree()
is displayed as text instead of rendered bullets. How can this be fixed?
Furthermore, is this approach of constructing the HTML tree considered optimal? It seems like there should be a way to accomplish this purely within the Angular view file without embedding HTML in the Javascript logic.
For a live example, check out the JSFiddle