2015-10-04 252 views
2

我在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": [] 
      }] 
     } 
    ] 
} 

所有我想要的只是知道如何使NG-重复孩子的孩子吗?

+0

有多少级的孩子?据我所知,你不能使用'ng-repeat'递归。 –

+0

那些孩子可以动态生成。所以我没有任何想法应该在那里! –

+0

谷歌'角递归树'应该找到很多的解决方案,模块,指令等 – charlietfl

回答

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> 

JSFiddle here

+0

这是很好的解决方案 –

+0

哇。没有其他的话。 –

0

所以它竟把你有数据可以使用NG重复使用的模板。这里有一个例子:

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阵列,使得它的工作。

+0

谢谢你们!我会试试看!真的感谢! –