AngularJS ng-repeat for dynamic child json array

AngularJS ng-repeat for dynamic child json array

本文关键字:json array child dynamic ng-repeat for AngularJS      更新时间:2023-09-26

我有一个动态JSON,它包含名称列表,它还包含子名称作为子集。如何使用angularJS ng-repeat在HTML UI中显示它

示例动态 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>

注意:JSON 是根据请求生成的。子数组是 可选,可能包含长度"n">

您可以通过添加 ng-if 指令来改善您的答案,因为child可选的。当然,它不会对你的应用程序产生任何影响,但这是一种很好的编码方式。

另外,而不是在ul上添加ng-repeat,它应该在 li .循环单个列表的ul是没有意义的。

请参考此处的示例。

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

更正的答案

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