我对 Angular 不熟悉。但是负责我项目的前端开发人员坚持认为他想要这样的 json:
{
"data": [{
"area1": {
"rows": [{
"the_desc": "A value 1",
"value": "sample value 1"
}, {
"the_desc": "A value 2",
"value": "sample value 2"
}, {
"the_desc": "A value 3",
"value": "other 3"
}, {
"the_desc": "A value 4",
"value": "other 4"
}, {
"the_desc": "A value 5",
"value": "other goats fly"
}, {
"the_desc": "A value 6",
"value": "bla blah"
}, {
"the_desc": "A value 7",
"value": "other 7"
}, {
"the_desc": "A value 8",
"value": "other 8"
}]
}
}, {
"area2": {
"rows": [{
"the_desc": "A value 9",
"value": "sample value 9"
}, {
"the_desc": "A value 10",
"value": "sample value 10"
}, {
"the_desc": "A value 11",
"value": "other 11"
}, {
"the_desc": "A value 12",
"value": "other 12"
}, {
"the_desc": "A value 13",
"value": "other goats fly 13"
}, {
"the_desc": "A value 14",
"value": "bla blah"
}, {
"the_desc": "A value 15",
"value": "other 15"
}, {
"the_desc": "A value 16",
"value": "other 16"
}]
}
}]
}
我认为我们应该摆脱像“the_desc”和“value”这样的重复字符串,并使用:
{
"data": [{
"area1": [
["1", "2"],
["3", "4"]
]
}, {
"area2": [
["21", "22", "a5"],
["23", "24", "b6"]
]
}]
}
但他坚持认为 NG-repeat 无法获取内部数组(它们是已知的列行数据。可能是 [][] 表数据。 问题:像 Angular 1 中那样获取数据有任何问题吗?没有嵌套的 NG 重复。如果我说每个区域的列都是固定的,会有什么不同吗?有没有办法遍历行,并按索引访问列?在我们的例子中,每个区域的列数都是已知的(页面上的表格)。
原因:来自服务器的负载较少。更快的网络数据传输。
在两个答案的帮助下得到它,在 https://plnkr.co/edit/DrsXTP4kD0CnyAQwuoSu?p=preview 上进行实验和可爱的 Angular 错误报告:https://docs.angularjs.org/error/ngRepeat/dupes?p0=ele%20in%20data.data%5B1%5D.area2%5B0%5D&p1=string:col%203%20A&p2=col%203%20A .
解决方案的要点:
在 js Controller 中:
$scope.data = {
"data": [{"area1":
[[ "A value 1",...
和 HTML:
<div class= "" ng-repeat="ele in data.data[1].area2 track by $index">
<span class='d2'> {{(ele[0])}} </span><span class='d2'> {{(ele[1])}}...
最佳答案
作为前端开发,我也会选择第一种结构。在任何情况下,您都必须像这样使用嵌套的 ng-repeat:
<div class="area" ng-repeat="area in data">
<div class="row" ng-repeat="row in area.rows">
<p class="description">{{::row.the_desc}}</p>
<p class="value">{{::row.value}}</p>
</div>
</div>
对于第二个片段:
<div class="area" ng-repeat="area in data">
<div class="row" ng-repeat="(key, value) in area.rows">
<p class="description">{{::key}}</p>
<p class="value">{{::value}}</p>
</div>
</div>
对于第 3 个片段,只要数组结构保持不变且只有两个值,我们就可以通过索引访问它们。
<div class="area" ng-repeat="(key,area) in data">
<!-- Prints area1, area2 if necessary -->
<p>{{key}}</p>
<!-- Prints 1st and 2nd value of the area array -->
<div class="row" ng-repeat="row in area">
<p class="description">{{row[0}}</p>
<p class="value">{{row[1]}}</p>
</div>
</div>
是否可以在没有嵌套的 ng-repeat 的情况下实现这一目标?不见得。嵌套数组过多。
但老实说,我不认为在对象键中存储一个“值”是一个好习惯(即使它可以用 Angular 显示),所以我建议你听从你的开发者的建议并使用第一个结构.
关于javascript - Angular 1 : populate table with ng-repeat using a 2-d array from server's json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39474480/