这是我的JSON数据格式。
{
"0": {
"id": "1",
"image": "/images/brands/surf_excel.png",
"name": "Surf Excel",
"productCount": "6"
},
"1": {
"id": "2",
"image": "/images/brands/rin.png",
"name": "Rin",
"productCount": "5"
},
"2": {
"id": "3",
"image": "/images/brands/ariel.png",
"name": "Ariel",
"productCount": "4"
}
}
当我尝试像这样分配这些数据时..
$scope.Brands = [];
$scope.Brands = data; // Not an array error
基本上我想逐个分配数据和访问。
如何解决此错误?
答案 0 :(得分:2)
您可以使用循环
angular.forEach(data,function(value,key){
$scope.Brands.push(value);
})
答案 1 :(得分:1)
永远记住,只要有数组,它就会被方括号[
]
包围。
现在您可以看到为什么您的JSON数据不包含任何数组。您可以按以下方式推送值:
,而不是直接将JSON的数据分配给$scope.Brands
。
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
var data = JSON.parse('{"0":{"id":"1","image":"/images/brands/surf_excel.png","name":"Surf Excel","productCount":"6"},"1":{"id":"2","image":"/images/brands/rin.png","name":"Rin","productCount":"5"},"2":{"id":"3","image":"/images/brands/ariel.png","name":"Ariel","productCount":"4"}}');
$scope.name = 'World';
$scope.Brands = [];
angular.forEach(data,function(value,key){
$scope.Brands.push(value);
})
document.write("<pre>" + JSON.stringify($scope.Brands, 0, 8) + "</pre>");
});
&#13;
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl"></body>
</html>
&#13;
现在,当您运行此代码段时,您会看到[
和]
所包围的数据。这表明它是一个数组。
答案 2 :(得分:0)
鉴于你正在使用棱角分明,@ SHS已经给出了最好的答案。解决这个问题的另一种方法是(非角度):
var brands = new Array();
//Get the keys and iterate through them and add each entry
Object.keys(data).forEach(function(key){
brands.push(data[key]);
});