0

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'

3
  • Its not a valid JSON. Commented Feb 15, 2016 at 9:24
  • @Rajesh I Updated the JSON... Commented Feb 15, 2016 at 9:27
  • You can try something like this: JSFiddle Commented Feb 15, 2016 at 9:29

2 Answers 2

1

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"
       }
    ];
});
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.