在表格中使用ng-repeat显示层次结构

时间:2015-10-07 11:54:15

标签: angularjs html-table ng-repeat

我需要在html表中显示存储在json对象中的一些分层数据。我尝试使用jsfiddle中的以下代码:http://jsfiddle.net/mrajcok/vGUsu/

//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

我应该能够遍历尽可能多的级别并在表格中显示它们。我怎么能这样做?

1 个答案:

答案 0 :(得分: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>

输出:

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

您还可以找到我的plunker here