2015-10-04 235 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

謝謝你們!我會試試看!真的感謝! –