gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:41:13 26 4
gpt4 key购买 nike

我有一个动态 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>

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

最佳答案

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

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

请引用样本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"
}
];
});

关于javascript - AngularJS ng-repeat 用于动态子 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35405297/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com