使用 ng-repeat 和嵌套循环添加行 [英] Adding rows with ng-repeat and nested loop
本文介绍了使用 ng-repeat 和嵌套循环添加行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种向表格添加行的方法.我的数据结构如下所示:
I'm looking for a way to add rows to a table. My data structure looks like that:
rows = [
{ name : 'row1', subrows : [{ name : 'row1.1' }, { name : 'row1.2' }] },
{ name : 'row2' }
];
我想创建一个看起来像这样的表:
I want to create a table which looks like that:
table
row1
row1.1
row1.2
row2
angular js ng-repeat 可以实现吗?如果不是,那么这样做的角度"方式是什么?
Is that possible with angular js ng-repeat? If not, what would be a "angular" way of doing that?
展平数组将是一个糟糕的解决方案,因为如果我可以遍历子元素,我可以在单元格、其他 css 类等中使用不同的 html 标签.
Flatten the array would be a bad solution because if i can iterate over the sub elements i could use different html tags inside the cells, other css classes, etc.
推荐答案
您将无法使用 ng-repeat 执行此操作.但是,您可以使用指令来实现.
You won't be able to do this with ng-repeat. You can do it with a directive, however.
<my-table rows='rows'></my-table>
小提琴.
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)
}
}
});
这篇关于使用 ng-repeat 和嵌套循环添加行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文