【发布时间】:2014-11-11 14:24:15
【问题描述】:
如果我的 JSON 看起来像这样,我该如何使用 ng-repeat
[
{
"id": "1",
"shop_name": "Shop Name",
"user_id": "2",
"shop_email": "",
"shop_address": "",
"shop_phone": "",
"company_name": "",
"description": "",
"shop_provision": null,
"created_at": "2014-11-05 10:32:32",
"updated_at": "2014-11-06 21:02:00",
"banners": [
{
"id": "18",
"disk_name": "545be1dfa2011452107756.png",
"file_name": "Screenshot from 2014-11-06 09:50:48.png",
"file_size": "135441",
"content_type": "image/png",
"title": null,
"description": null,
"field": "banners",
"sort_order": "18",
"created_at": "2014-11-06 21:02:23",
"updated_at": "2014-11-06 21:02:34",
"path": "/uploads/public/545/be1/dfa/545be1dfa2011452107756.png",
"extension": "png"
},
{
"id": "20",
"disk_name": "545be1e6b5048131391528.png",
"file_name": "Screenshot from 2014-11-06 09:50:48.png",
"file_size": "135441",
"content_type": "image/png",
"title": null,
"description": null,
"field": "banners",
"sort_order": "20",
"created_at": "2014-11-06 21:02:30",
"updated_at": "2014-11-06 21:02:34",
"path": "/uploads/public/545/be1/e6b/545be1e6b5048131391528.png",
"extension": "png"
}
]
}
]
在横幅上我想再次迭代
在控制器上,我得到一个 JSON 对象或数组,其中包含一个子对象 (responseJSON)
october.controllers['dashboard/wm'] = function ($scope, $request) {
$scope.banners = $request('onGetBanners'); //the $request is an ajax function
console.log($scope.banners);
}
子对象
responseJSON 看起来像 firebug 控制台中的结果
Object { result="[{"id":"1","shop_name":"...","extension":"png"}]}]"}
从这一切中我想要结果=
比我尝试迭代范围像
<div ng-repeat="banner in banners.responseJSON.result track by $index"></div>
更新
我在控制器中启动范围时改变了方式
october.controllers['publishers/wm'] = function ($scope, $request) {
$request('onGetBanners', {success: function(data){
this.success(data).done(function() {
$scope.response = data.result;
});
}})
}
而不是再次尝试迭代
{% verbatim %}
{{response}} //outputs
[
{
"id": "2",
"shop_name": "Test Shop",
"user_id": "1",
"shop_email": null,
"shop_address": null,
"shop_phone": null,
"company_name": null,
"description": "",
"shop_provision": null,
"created_at": "2014-11-05 11:31:15",
"updated_at": "2014-11-05 11:31:15",
"banners": []
}
]
<div ng-repeat="shop in response track by $index">
{{ shop.shop_name }} //no data
</div>
{% endverbatim %}
如果我删除 track by $index 我会得到 p>
Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: shop in response, Duplicate key: string:", Duplicate value: "\""
明白了,我永远不会忘记这种痛苦
angular.fromJson(jsondata)
【问题讨论】:
-
所以你有一个控制器来设置
$scope.responseJSON = json;?你能告诉我们控制器吗? -
是的,范围看起来像这样
-
对不起,我必须纠正自己,我会更新帖子
-
$request是否异步?此外,banners 变量似乎存储的是商店而不是横幅,变量命名对于可读性很重要 -
是的 $request 是异步的。是一个在迭代时检索远程数据的 ajax 函数,我将更改变量名。我正在从控制器绑定以直接使用结果启动范围,但不知何故不起作用
标签: json angularjs angularjs-ng-repeat