2016-08-18 80 views
1

我有一個菜單,使用ulli。我想通過Angular和JSON對象來顯示它。如何通過Angular Js顯示n層嵌套json對象?

我嘗試做ng-repeat但我的問題是,如果我的對象有20層嵌套對象或在另一方面它有n層嵌套的孩子如何顯示它?

代碼HTML

<ul> 
    <li ng-repeat="item in model"> 
    {{item.text}} 
    </li> 
</ul> 

和我的JSON對象是:

var model = [ 
    { text: "one", link: "#" }, 
    { text: "tow", link: "#" }, 
    { 
     text: "three", 
     link: "#", 
     children: [ 
      { text: "four", link: "#" }, 
      { text: "five", link: "#", children: [{text:"nine", link:"#"}] }, 
      { text: "six", link: "#" } 
     ] 
    }]; 

$scope.model = model; 
+0

可能的重複http://stackoverflow.com/questions/34737227/using-ng-repeat-how-to-retrieve-data-from-nested-json-object?rq=1 –

+0

@steady_daddy你的答案是不正確的,因爲它僅支持2層 – Motion

回答

1

您可以在控制器上創建HTML,然後將其綁定到視圖與NG綁定,HTML

我會建議一個遞歸方法:

'use strict'; 

angular.module('yourApp') 
.controller('FooCtrl', function($scope) { 
    var myModel = [ 
     { text: "one", link: "#" }, 
     { text: "tow", link: "#" }, 
     { 
      text: "three", 
      link: "#", 
      children: [ 
       { text: "four", link: "#" }, 
       { text: "five", link: "#", children: [{ text: "nine", link: "#" }] }, 
       { text: "six", link: "#" } 
      ] 
     } 
    ]; 
    var createHtml = function(model) { 
     var html = ''; 
     for(var i = 0 ; i < model.length ; i++) { 
      var li = model[i]; 
      html += '<li>'; 
      html += li.text; 
      if(li.children) { 
       html += '<ul>'; 
       html += createHtml(li.children); 
       html += '</ul>'; 
      }; 
      html += '</li>'; 
     } 
     return html; 
    } 
    $scope.myHtml = '<ul>'+createHtml(myModel)+'</ul>'; 
}); 

,你可以用

<div ng-bind-html="myHtml"> 
</div> 
0

一個好的方法來處理這個稱呼它在你的觀點應遵循composite pattern原則:

<composite-list items="model"> </composite-list> 

與定義如下組合元素:

const compositeList = { 
    scope: { 
     items: "=" 
    }, 
    restrict: 'E', 
    template: ` 
     <ul> 
      <li ng-repeat="item in vm.items"> 
       <a ng-href="{{item.link}}">{{item.text}}</a> 
       <composite-list ng-if="item.children.length" items="item.children"> 
       </composite-list> 
      </li> 
     </ul> 
    ` 
} 

編輯:不是嚴格的實施,但它的工作