我正在尝试将 JSON 代码显示到 html 表格中。我有这个 JSON:
posts:[
{
"category":[],
"status":[]
},
{
"category":
[
{
"ID_post":"2",
"category":"5 Reasons",
"ID_cat":"1"
},
{
"ID_post":"2",
"category":"Advertising",
"ID_cat":"2"
}
],
"status":
[
{
"ID_post":"2",
"status":"Approved",
"ID_stat":"1",
"color":"red"
},
{
"ID_post":"2",
"status":"Placed",
"ID_stat":"2",
"color":"#1800fb"
}
]
}
]
我想在 html 表格中显示状态的颜色,如下所示:
<tr>
<th>Web Status</th>
</tr>
<tbody ng-repeat="post in posts | startFrom: start | limitTo: limit">
<tr>
<td>{{post.status}}</td>
</tr>
</tbody>
它在第二篇文章中返回类似这样的内容:
[{"ID_post":"2","status":"Approved","ID_stat":"1","color":"red"},{"ID_post":"2","status":"Placed","ID_stat":"2","color":"#1800fb"}]
但我需要每个帖子的颜色。我怎么才能得到它?我尝试使用 post.status.color 但它不起作用。 有人能帮我吗? 谢谢!
最佳答案
如果您想要在表格中显示的全部是每个状态的颜色,您可以采取的一种方法是在单独的数组中捕获“状态”数据,例如 $ scope.statuses = posts[1].status
。然后在 HTML 中循环访问该数组:
<tbody ng-repeat="status in statuses| startFrom: start | limitTo: limit">
<tr>
<td>{{status.color}}</td>
</tr>
</tbody>
根据您当前的数据结构,posts
是一个包含两个元素的数组。 ng-repeat 直接循环遍历该数组中的每个元素。第一个元素 posts[0]
是一个具有两个空数组属性的对象。因此,第一个 {{post.status}}
为空。第二个元素 posts[1]
也是一个具有属性“category”和 status 的对象,每个属性都具有填充的数组。使用第二个元素,{{post.status}}
将显示 posts[1].status
中的所有数据。
再说一次,如果您需要显示的只是每个状态的颜色,那么最简单的方法是在单独的变量中捕获 posts[1].status
。如果需要显示类别数据和状态数据,则可能需要将这两个数组合并为一个数组。请参阅以下示例:In Angular, how do you loop through two arrays to populate a third?
关于javascript - 如何在 html Angular 中显示嵌套的 json 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37257808/