简体   繁体   中英

AngularJS ng-repeat for dynamic child json array

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'

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"
       }
    ];
});

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM