我对angularJs中的递归有问题。
我想重复JSON文件中的所有名称: 这是我的JSON文件结构:
var data = {
"id": "580",
"name": "test",
"status": "ACTIVE",
"parentId": null,
"children": [
{
"id": "581",
"name": "test 2",
"status": "ACTIVE",
"parentId": "580",
"children": [{
"id": "594",
"name": "test 3",
"status": "ACTIVE",
"parentId": "581",
"children": []
}]
}
]
}
我想要的只是知道如何在儿童中制作重复儿童?
答案 0 :(得分:3)
您应该使用ng-template以递归方式使用它。
<script type="text/ng-template" id="exampleTree">
{{ x.name }}
<ul ng-if="x.children">
<li ng-repeat="x in x.children" ng-include="'exampleTree'">
</li>
</ul>
</script>
要使用此模板并运行它:
<ul>
<li ng-repeat="x in data" ng-include="'exampleTree'"></li>
</ul>
答案 1 :(得分:0)
您可以将ng-repeat与模板一起使用,以便尽可能地获取数据。这是一个例子:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.child = {
"id": "580",
"name": "test",
"status": "ACTIVE",
"parentId": null,
"children": [{
"id": "581",
"name": "test 2",
"status": "ACTIVE",
"parentId": "580",
"children": [{
"id": "594",
"name": "test 3",
"status": "ACTIVE",
"parentId": "581",
"children": []
}]
}]
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" ng-controller="MainCtrl">
<!-- This is the template that can be repeated in itself-->
<script type="text/ng-template" id="childView">
{{child.name}}
<ul>
<li ng-repeat="child in child.children" ng-include="'childView'"></li>
</ul>
</script>
<!-- This is the initial use for the template-->
<div ng-include="'childView'"></div>
</body>
我必须将子594放在一个数组中才能工作。