Javascript 无法访问angularjs数组中的json数据
我已成功返回一个json对象,该对象包含来自数据库的查询结果。我无法逐个访问返回的json 以下是Javascript 无法访问angularjs数组中的json数据,javascript,angularjs,json,angular-http,Javascript,Angularjs,Json,Angular Http,我已成功返回一个json对象,该对象包含来自数据库的查询结果。我无法逐个访问返回的json 以下是console.log显示的内容: 角度代码: $scope.peopleList=[]; $http.get("http://localhost/project/public/people_names").then(function(response) { $scope.peopleList.push(response.data);
console.log
显示的内容:
角度代码:
$scope.peopleList=[];
$http.get("http://localhost/project/public/people_names").then(function(response) {
$scope.peopleList.push(response.data);
});
console.log($scope.peopleList);
如果我使用console.log($scope.peopleList[0])代码>,它表示未定义
。如何使用ng repeat
访问它以打印它请尝试以下代码:
$scope.peopleList=[];
$http.get("http://localhost/project/public/people_names")
.then(function(response) {
$scope.peopleList = response.data;
console.log($scope.peopleList);
});
<div ng-repeat='person in peopleList track by person.id'>
....
</div>
并像下面一样使用ng repeat
<div ng-repeat='person in peopleList track by person.id'>
....
</div>
....
一些观察结果:
- 作为
响应。数据
已经是一个对象数组
。因此,无需再次将其推入不同的阵列
- 您可以直接使用
$scope.peopleList=response.data
而不是$scope.peopleList.push(response.data)
现在,如果您尝试从数组访问第一个对象,您可以使用console.log($scope.peopleList[0])
它将为您提供预期的结果
演示
var myApp=angular.module('myApp',[]);
myApp.controller('MyCtrl',函数($scope){
$scope.peopleList=[{
id:5,
姓名:“拉曼”
},
{
id:7,
姓名:“科马尔”
}];
log($scope.peopleList[0]);
});代码>
这是因为您正在执行异步调用,请尝试使用console.log
,但要在其中进行。只需将响应对象中的数据属性分配给peopleList,而不是按。然后,您可以使用ng repeat
可能重复的