我想设计一个基于 Controller 的表。基本上是一个简单的 Controller ,例如:
function Main($scope) {
$scope.row = {
columns: [{
type: 'single',
name: 'col1'
}, {
type: 'double',
name: 'col2'
}]
};
}
I want to change the number of tr
s based on type of column. Basically the desired output is :
<table>
<tr>
<!-- for column in columns -->
<!-- If column.type is single have single td -->
<!-- If column.type is double have two td -->
<td>col1</td>
<td>col2</td>
<td>col2</td>
</tr>
</table>
我有一把 fiddle 你可以玩:http://jsfiddle.net/basarat/7G6fF/
我尝试过将 ng-repeat 与 span 一起使用,但问题是 span
被浏览器从 DOM 中删除,因为它是 tr 的无效子级:
<table>
<tr>
<!-- for column in columns -->
<!-- If column.type is single have single td -->
<!-- If column.type is double have two td -->
<span ng-repeat="column in row.columns">
<span ng-switch="column.type">
<span ng-switch-when="single"><td>{{column.name}}</td></span>
<span ng-switch-when="double"><td>{{column.name}}</td><td>{{column.name}}</td></span>
</span>
</span>
</tr>
</table>
最佳答案
我有一个使用 ng-repeat-start
和 ng-repeat-end
语法的工作示例。不是很优雅,但是根据您给定的数据集,这是我能想到的最好的:
<table>
<tr>
<td ng-repeat="column in row.columns | filter:isSingle">
{{column.name}}
</td>
<td ng-repeat-start="column in row.columns | filter:isDouble">
{{column.name}}
</td>
<td ng-repeat-end>
{{column.name}}
</td>
</tr>
</table>
isSingle
和 isDouble
过滤器函数在您的 Controller 中定义:
$scope.isSingle = function(column){
return column.type === 'single';
}
$scope.isDouble = function(column){
return column.type === 'double';
}
这是一个工作 fiddle sample : http://jsfiddle.net/7G6fF/3/
更新
根据评论中的 @PeterAlbert 问题,我能够保持顺序的唯一方法是将列数据转换为更兼容 ngRepeat
的格式。有点受@MadaManu 回答的启发。老实说,我认为这是一条必走之路。下面的示例在 Controller 内转换列数据,这很好,但显然您也可以在服务器端对其进行格式化。
改变你的专栏:
$scope.row = {
columns: [{
type: 'single',
name: 'col1'
}, {
type: 'double',
name: 'col2'
}]
};
$scope.transformedColumns = [];
$scope.$watchCollection('row.columns', function (newColumns, oldColumns) {
$scope.transformedColumns = transformColumns(newColumns);
});
function transformColumns(columns) {
var c = [];
angular.forEach(columns, function (column) {
if (column.type === 'single') {
c.push(column);
} else if (column.type === 'double') {
c.push(column);
c.push(column);
}
});
return c;
}
一旦转换,只需在 html 中使用标准 ngRepeat
语法即可:
<table>
<tr>
<td ng-repeat="column in transformedColumns track by $index">
{{column.name}}
</td>
</tr>
</table>
更新后的fiddle is here : http://jsfiddle.net/7G6fF/5/出于测试目的,我添加了两个按钮来添加单列或双列,以便您可以实时查看影响,这也是 fiddle 中 $scope.$watchCollection
代码的原因。
关于angularjs - 使用angularjs修改html表格的列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21986164/