1

Suppose I have the following JSON structure in my javascript as a variable named myTree:

[
    {"name": "A", "children": [
            {"name": "C", "children": []},
            {"name": "D", "children": []},
        ]
    },
    {"name": "B", "children": []}
]

I would like to use AngularJS to render it as the following HTML. How can I do it? FYI, the tree can have arbitrary depth. I have shown only a very simple example here.

<ul>
    <li>
        A
        <ul>
            <li>C</li>
            <li>D</li>
        </ul>
    </li>
    <li>B</li>
</ul>
0

1 Answer 1

5

You should make recursive templates:

<script type="text/ng-template" id="item_template">
 {{child.name}}
 <ul>
    <li ng-repeat="child in child.children" ng-include="'item_template'">
    </li>
  </ul>
</script>

<ul>
  <li ng-repeat="child in myTree" ng-include="'item_template'">
  </li>
</ul>

So, you will render 'infinite' levels of recursion, no only the first level.

Sign up to request clarification or add additional context in comments.

2 Comments

How is this recursive? I don't see any function calling itself here. For it to be recursive, there would have to be a calll from within the <li ng-repeat="child in children"></li> to item_template.
@Saqib Ali: It was missing a ng-include attribute on the <li> inside the template.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.