【发布时间】: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