我想从具有以下方案的数组构建一个表:
var items = [
{
name: 'xxx',
configurations: [
{
image: 'aaa.jpg'
},
{
image: 'bbb.jpg'
},
...
]
},
{
name: 'yyy',
configurations: [
{
image: 'ccc.jpg'
},
{
image: 'ddd.jpg'
},
...
]
},
...
]
我想用所有元素的所有图像获得一行(每个图像都嵌套在一个 <td>
中,例如:
<tr>
<td>
<img src="aaa.jpg">
</td>
<td>
<img src="bbb.jpg">
</td>
<td>
<img src="ccc.jpg">
</td>
<td>
<img src="ddd.jpg">
</td>
</tr>
如何用 Angular 来做到这一点?到目前为止我的代码如下所示:
<tr>
<td ng-repeat-start="proposition in items">
<img ng-src="{{::proposition.configurations[0].image}}" />
</td>
<td ng-repeat-end>
<img ng-src="{{::proposition.configurations[1].image}}" />
</td>
</tr>
但显然有一些configurations
在proposition
是动态的,那么我如何迭代它,保持相同的 html 方案?
最佳答案
您必须运行两个 ng-repeat,一个用于项目,另一个用于配置。
编辑
最简单的方法是展平数组。
因此,您将拥有一个包含 <image, name>
元组的长数组。
您可以使用 map 来做到这一点:
这是代码:
$scope.items = [
{
name: 'xxx',
configurations: [
{
image: 'yyy.jpg'
},
{
image: 'yyy2.jpg'
}
]
},
{
name: 'yyy',
configurations: [
{
image: 'zzz.jpg'
},
{
image: 'zzz2.jpg'
}
]
},
];
$scope.items = $scope.items.map(function(item){
return item.configurations.map(function(inner){
return { name: item.name, image: inner.image};
})
})
$scope.items = $scope.items.concat.apply([], $scope.items);
您有一个完整的工作示例 here .
关于javascript - 使用 ng-repeat in Angular 从二维数组构建表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36999664/