angularjs - 在 Angular 中循环遍历 JSON 对象
问题描述
我有一个产品循环,效果很好。
<div ng-repeat="result in results track by result.uid">
<img ng-src="{{ result.img';" alt="{{ result.name }}"
title="{{ result.name }}" />
<p><span class="money">£{{ result.price | number:2 }}</span></p>
<p class="product-title">
<a ng-href="{{ result.url }}">{{ result.name }}</a>
</p>
</div>
在循环中,有一个包含 JSON 数据的对象。
{{result.colours}}
这包含以下内容:
[
{
"id":866337128495,
"title":"Product Title",
"handle":"product-url",
"image":"/img.jpg",
"sku":"SKU001",
"name":"Product Name",
"type":"one_color",
"data":"#000000"
},
{
"id":866337128496,
"title":"Product Title2",
"handle":"product-url2",
"image":"/img2.jpg",
"sku":"SKU002",
"name":"Product Name 2",
"type":"one_color",
"data":"#000000"
}
]
我需要遍历这个,并尝试过:
<div ng-init="swatches=result.colours">
<div ng-if="swatches">
<div ng-repeat="(key,value) in swatches">
{{key}}:{{value}}
</div>
</div>
</div>
这只是返回:
0: [
{
"id":866337128495,
"title":"Product Title",
"handle":"product-url",
"image":"/img.jpg",
"sku":"SKU001",
"name":"Product Name",
"type":"one_color",
"data":"#000000"
},
{
"id":866337128496,
"title":"Product Title2",
"handle":"product-url2",
"image":"/img2.jpg",
"sku":"SKU002",
"name":"Product Name 2",
"type":"one_color",
"data":"#000000"
}
]
我是 Angular 的新手,但是我研究了很多不同的可能性来做到这一点,但都达不到要求。任何想法都会受到欢迎!
解决方案
angular.module("app", [])
.run(function($rootScope) {
$rootScope.results = [
{
name: "Demo",
colors: [{
"id": 866337128495,
"title": "Product Title",
"handle": "product-url",
"image": "/img.jpg",
"sku": "SKU001",
"name": "Product Name",
"type": "one_color",
"data": "#000000"
},
{
"id": 866337128496,
"title": "Product Title2",
"handle": "product-url2",
"image": "/img2.jpg",
"sku": "SKU002",
"name": "Product Name 2",
"type": "one_color",
"data": "#000000"
}
]
}
]
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app">
<div ng-repeat="result in results track by result.uid">
{{result.name}}
<div ng-init="swatches=result.colors">
<div ng-if="swatches">
<div ng-repeat="swatch in swatches">
<div ng-repeat="(key, value) in swatch">
{{key}}:{{value}}
</div>
<br>
</div>
</div>
</div>
</div>
</div>
推荐阅读
- laravel - Laravel 5.7 从存储中获取图像
- xplane - xplane11控制飞行员飞机冻结松动设置
- python - Python protobuf 解码 base64 字符串
- flutter - 我收到一个错误,名为没有属性“BoxShadow”。我有一个代码如下:
- typescript - 重复页面的 React Native Typescript 上的导航结构
- xml - Mule 4 嵌套 XML 模式导入在 APIKit 路由器中失败
- php - 如何在 $_POST 中搜索动态添加的输入值?
- sql - 计算一周内花费的总时间
- node.js - 30 分钟后从集合中删除数据
- list - 如何在颤动中仅显示列表的 5 项