简体   繁体   English

用于动态子json数组的AngularJS ng-repeat

[英]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. 我有一个动态JSON,其中包含名称列表,还包含子名称作为子集。 How can I show it in the HTML UI using angularJS ng-repeat 如何使用angularJS ng-repeat在HTML UI中显示它

The Sample Dynamic JSON is 示例动态JSON是

$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. 注意:JSON是基于Request生成的。 The Child array is Optional and it may contain the length 'n' 儿童阵列是可选的,它可以包含长度“N”

You can better your answer by adding an ng-if directive, as the child is optional . 您可以通过添加ng-if指令来更好地解决问题,因为child可选的 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 . 另外,应该在li代替在ul上添加ng-repeat It makes no sense in looping the ul for a single list. 在循环ul以获得单个列表时没有任何意义。

Please refer the sample here . 请在这里参考样本。

HTML: 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: 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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