gpt4 book ai didi

javascript - 如何在 angularjs 中使用 ng-repeat 以表格格式引入嵌套的项目数组?

转载 作者:行者123 更新时间:2023-12-02 17:58:22 25 4
gpt4 key购买 nike

我想使用 ng-repeat 为每个位置带来项目表。我无法使用 ng-repeat 对于以下结构来解决它。请有人帮助我。提前致谢。

结构是。

$scope.locations = [
// Location #1
[
{
location:"location1",
delar:"delar-x",
items:[
{
name:"Iphone",
price:124
},
{
name:"Blackbery",
price:132
}
]
},
{
location:"location1",
delar:"delar-y",
items:[
{
name:"Headphone",
price:10
},
{
name:"Cabels",
price:112
}
]
}
],
// Location #2
[
{
location:"location2",
delar:"delar-x",
items:[
{
name:"Iphone",
price:124
},
{
name:"Blackbery",
price:132
}
]
},
{
location:"location2",
delar:"delar-y",
items:[
{
name:"Headphone",
price:120
},
{
name:"Cabels",
price:110
}
]
}
]
]

我如何引入以下格式?

<div>
<h1> location1 </h1>
<table>
<tr>
<td> Iphone </td>
</tr>
<tr>
<td> Blackbery </td>
</tr>
<tr>
<td> Headphone </td>
</tr>
<tr>
<td> Cabels </td>
</tr>
</table>
<h1> location2 </h1>
<table>
<tr>
<td> Iphone </td>
</tr>
<tr>
<td> Blackbery </td>
</tr>
<tr>
<td> Headphone </td>
</tr>
<tr>
<td> Cabels </td>
</tr>
</table>
<div>

最佳答案

您可以采用两步方法

<div>
<h1 ng-repeat-start="loc in locs"> {{loc.location}} </h1>

<table ng-repeat-end>
<tr ng-repeat="item in loc.items">
<td>{{item.name}}</td>
</tr>
</table>
</div>

然后规范化位置数组

$scope.locations = [....];

//normalize the locations array to a format which can be easily iterated using ng-repeat
var map = {}, array=[];
angular.forEach($scope.locations, function(obj){
angular.forEach(obj, function(obj){
var items = map[obj.location];
if(!items){
items = map[obj.location] = [];
array.push({
location: obj.location,
items:items
})
}
console.log(obj)
angular.forEach(obj.items, function(item){
items.push(item);
})
});
})
$scope.locs = array;

演示:Fiddle

关于javascript - 如何在 angularjs 中使用 ng-repeat 以表格格式引入嵌套的项目数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20799094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com