我需要从一组对象创建一个表,但我不想对表进行硬编码。例如,我无法this或this。我宁愿需要嵌套的ng-repeats,如this。但我的情况有点不同,因为我的列包含数组中的两个值。数据如下所示:
[
{
"foo":"bar",...,
"key1":[
"value1",
"value2"
],
"key2":[
"value1",
"value2"
],...,
"more_foo":"more_bar"
},...
]
我希望表行中数组的所有对象(总是具有相同结构)的值(总是字符串),其中每个键应该是列名。像这样:
table,
th,
td {
border: 1px solid black;
text-align: center;
border-spacing: 0;
}
td,
th {
padding: 0.5em;
}

<table>
<thead>
<tr>
<th>foo</th>
<th colspan="2">key1</th>
<th colspan="2">key2</th>
<th>more_foo</th>
</tr>
</thead>
<tbody>
<tr>
<td>bar</td>
<td>value1</td>
<td>value2</td>
<td>value1</td>
<td>value2</td>
<td>more_bar</td>
</tr>
</tbody>
</table>
&#13;
以下是我的想法:
<table>
<thead>
<tr>
<th ng-repeat="(propName, prop) in myArray[0]"
colspan="{{isUpdateable(propName) ? 2 : undefined}}"> {{propName}}
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="object in myArray | filter: searchFilter">
<td ng-repeat="(propName, prop) in object" double-col>{{prop}}</td>
</tr>
</tbody>
</table>
如果此值是数组,则 isUpdatable(propName)
将返回true,否则返回false。这样就可以在此列中有两个td
。
双重指令:
app.directive('double-col', function () {
return {
transclude: true,
template: "<td>{{prop[0]}}</td><td class=\"changedProp\">{{prop[1]}}</td>"
};
});
我希望此指令将现有的td
替换为两个td
,当且仅当prop
是数组时,否则无法显示prop
(请参阅{上面{1}}。
因为您在https://stackoverflow.com(人们发布的内容尚不合适的地方),您可能会猜到我当前的代码并不能很好地工作。我也是angularJS的新手,并且基本上不了解自定义指令(也可能是大多数其他的东西),所以如果有人可以帮我解决这个问题并提供解释,那就太好了。
答案 0 :(得分:1)
怎么样?
<tr ng-repeat="object in myArray | filter: searchFilter">
<td ng-repeat="(propName, prop) in object" colspan="{{isArray(prop) ? prop.length : 1}}">
<span ng-if="!isArray(prop)"> {{prop}}</span>
<table ng-if="isArray(prop)"><tr>
<td ng-repeat="prop1 in prop">
{{prop1}}
</td>
</tr></table>
</td>
</tr>
$scope.isArray=function(prop){
return Array.isArray(prop);
}