【问题标题】:Showing a hierarchy using ng-repeat in a table在表格中使用 ng-repeat 显示层次结构
【发布时间】:2015-10-07 22:11:10
【问题描述】:

我需要在 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

我应该能够遍历尽可能多的关卡并将它们显示在表格中。我该怎么做?

【问题讨论】:

    标签: angularjs html-table ng-repeat


    【解决方案1】:

    看起来你有一个树形的数据结构,你可以用递归函数来解决它来探索你的树。

    我编写了以下代码,应该可以帮助您上路。我很确定通过使用额外的变量可以更优雅地完成它。

    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
    

    你也可以找到我的小伙伴here

    【讨论】:

    • 好主意,但这是一种很好的解决方法,更好的是我们应该有一些真正的 Angular 风格。感谢 skubski,如果您分享更多与 angularJS 相关的内容。
    • @ChetanSharma 确实,它可以以更 Angular 的方式实现,但基本思想将保持不变。我确定有一些项目,例如:angular-recursiveexample
    • 感谢您的宝贵回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2019-09-04
    • 2017-07-15
    • 2018-08-21
    • 2011-09-09
    • 1970-01-01
    相关资源
    最近更新 更多