2015-10-07 59 views
1

我需要在html表格中顯示存儲在json對象中的一些分層數據。我試着用下面的代碼的jsfiddle:http://jsfiddle.net/mrajcok/vGUsu/在表格中顯示使用ng-repeat的層次結構

//HTML 

<div ng-controller="MyCtrl"> 
<my-table rows='rows'></my-table> 
</div> 


//javascript 
    var myApp = angular.module('myApp', []); 

myApp.directive('myTable', function() { 
    return { 
    restrict: 'E', 
    link: function (scope, element, attrs) { 
     var html = '<table>'; 
     angular.forEach(scope[attrs.rows], function (row, index) { 
      html += '<tr><td>' + row.name + '</td></tr>'; 
      if ('subrows' in row) { 
       angular.forEach(row.subrows, function (subrow, index) { 
        html += '<tr><td>' + subrow.name + '</td></tr>'; 
       }) 
      } 
     }) 
     html += '</table>'; 
     element.replaceWith(html) 
    } 
} 
}); 

function MyCtrl($scope) { 
    $scope.rows = [ 
    { name: 'a', subrows: [{ name: 'a.1' }, { name: 'a.2' }] }, 
    { name: 'b', subrows: [{ name: 'b.1',subrows: [{ name: 'b.1.1' }, { name: 'b.1.2' }] }, { name: 'b.2' }] } 
]; 
} 

我得到的輸出:

a 
a.1 
a.2 
b 
b.1 
b.2 

但我需要得到:

a 
a.1 
a.2 
b 
b.1 
b.1.1 
b.1.2 
b.2 

我應該能夠爲穿越儘可能多的級別並將它們顯示在表格中。我怎樣才能做到這一點?

回答

2

看起來你有一個樹形的數據結構,你可以通過遞歸函數來解決它,以探索你的樹。

我寫了下面一段代碼,應該讓你在路上。我很確定可以通過使用其他變量來更加優雅地完成它。

JS:(不改變你的控制器)

var myApp = angular.module('myApp', []); 

myApp.directive('myTable', function() { 
    return { 
     restrict: 'E', 
     link: function (scope, element, attrs) { 
      var text = ''; 

      function tableRec(array) { 
       if(array.length === 0) { 
       return text; 
       } else { 
       var obj = array.shift(); 

       text += '<tr><td>' + obj.name + '</td></tr>'; 
       //if there are subrows we go deeper into the recursion 
       if(obj.subrows) { 
        tableRec(obj.subrows); 
       } 

       tableRec(array); 
       } 
      } 

      tableRec(scope[attrs.rows]); 

      var html = '<table>' + text + '</table>'; 

      element.replaceWith(html) 
     } 
     } 
    }); 

HTML:(不變)

<div ng-controller="MyCtrl"> 
    <my-table rows='rows'></my-table> 
</div> 

OUTPUT:

a 
a.1 
a.2 
b 
b.1 
b.1.1 
b.1.2 
b.2 

您也可以找到我的plunker here

+0

謝謝。它完美的作品。 –

+0

不錯的想法,但它是一種很好的解決方案,更好的是我們應該有一些Angular的真正味道。感謝skubski,如果你分享更多有關angularJS。 –

+0

@ChetanSharma事實上,它可以通過更加角度的方式來實現,但基本的想法將保持不變。我確定有一些項目,例如:[angular-recursive](https://github.com/marklagendijk/angular-recursion)[示例](http://plnkr.co/edit/JAIyolmqPqO9KsynSiZp?p =預覽)。 – skubski