How to iterate over multi-level nested JSON array?

335 Views Asked by At

I have a JSON array which has a structure like below:

[{"a":"b","child":[{"a":"c","child":["a":"d","child":[]]}]

This array have have any level of children and the levels are variable. Basically, I've built a JSON array over a site structure. I need to iterate over this list and build a HTML structure like below:

<ul>
 <li>
  <a href="b">
   <ul>
     <li>
       <a href="c">
         <ul>
           <li> <a href="d"> </li>
         </ul>
        </a>
       </li>
      </ul>
    </a>
  </li>
</ul>

Please let me know if this can be achieved in AngularJS using ng-repeat and ng-template.

1

There are 1 best solutions below

0
Nikhil Aggarwal On

Try following

var app = angular.module('testApp', []);

app.controller('MainCtrl', function($scope) {
  $scope.object = [{"a":"b","child":[{"a":"c","child":[{"a":"d","child":[]}]}]}];
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.14/angular.min.js"></script>
<div ng-app="testApp">
<div ng-controller="MainCtrl">
  <ul>
    <li ng-repeat="node in object" ng-include="'tree'"></li>
</ul>

<!-- recursive template -->
<script type="text/ng-template" id="tree">
    <a href="{{node.a}}">{{node.a}}
        <ul data-ng-if="node.child && node.child.length">
            <li ng-repeat="node in node.child" ng-include="'tree'"></li>
        </ul>
    </a>
</script>
</div>
</div>