I'm having a dynamic JSON, which contains the list of name, it also contains the children names as a subset. How can I show it in the HTML UI using angularJS ng-repeat

The Sample Dynamic JSON is

$scope.family = [
   {
      "name":"Siva",
      "child":[
         {
            "name":"Suriya"
         },
         {
            "name":"Karthick"
         }
      ]
   },
   {
      "name":"Kumar",
      "child":[
         {
            "name":"Rajini"
         },
         {
            "name":"Kamal"
         },
         {
            "name":"Ajith"
         }
      ]
   },
   {
      "name":"Samer"
   },
   {
      "name":"Mahesh"
   }
];

<div ng-repeat="members in family">
    <!-- How to Show it in the UI -->
</div>

Note: The JSON is generated based on Request. The Child array is Optional and it may contain the length 'n'

share|improve this question
    
Its not a valid JSON. – Rajesh Feb 15 '16 at 9:24
    
@Rajesh I Updated the JSON... – B.Balamanigandan Feb 15 '16 at 9:27
    
You can try something like this: JSFiddle – Rajesh Feb 15 '16 at 9:29

You can better your answer by adding an ng-if directive, as the child is optional. Of course, it won't make any impact to you app, but it is a good way to code.

Plus, instead of adding ng-repeat on ul, it should be in li. It makes no sense in looping the ul for a single list.

Please refer the sample here.

HTML:

<div ng-app="app" ng-controller="test">
    <ul ng-repeat="member in family">
        <li>
            {{member.name}}
            <span ng-if="member.child.length > 0">
                <ul>
                    <li ng-repeat="c in member.child">{{c.name}}</li>
                </ul>
            </span>
        </li>
    </ul>
</div>

JS:

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

app.controller('test', function ($scope) {
    $scope.family = [
       {
           "name": "Siva",
           "child": [
              {
                  "name": "Suriya"
              },
              {
                  "name": "Karthick"
              }
           ]
       },
       {
           "name": "Kumar",
           "child": [
              {
                  "name": "Rajini"
              },
              {
                  "name": "Kamal"
              },
              {
                  "name": "Ajith"
              }
           ]
       },
       {
           "name": "Samer"
       },
       {
           "name": "Mahesh"
       }
    ];
});
share|improve this answer
up vote 0 down vote accepted

The Corrected answer

<ul ng-repeat="member in family">
    <li>{{member.name}}
        <ul>
            <li ng-bind="c.name" ng-repeat="c in member.child"></li>
        </ul>
    </li>
</ul>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.