2016-08-18 71 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> 
    ` 
} 

编辑:不是严格的实施,但它的工作