我已经成功返回了一个json对象,该对象具有来自数据库的查询结果。我无法逐个访问返回的json。
角度代码:
$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]);
,则会显示undefined
。如何使用ng-repeat
答案 0 :(得分:1)
尝试以下代码:
$scope.peopleList=[];
$http.get("http://localhost/project/public/people_names")
.then(function(response) {
$scope.peopleList = response.data;
console.log($scope.peopleList);
});
并使用下面的ng-repeat
<div ng-repeat='person in peopleList track by person.id'>
....
</div>
答案 1 :(得分:0)
一些观察结果:
response.data
已经是 array of objects
。因此,无需再次将其推入不同的阵列。$scope.peopleList = response.data
代替$scope.peopleList.push(response.data)
现在,如果您尝试从阵列中访问第一个对象,则可以使用console.log($scope.peopleList[0])
,它将为您提供预期的结果。
<强>样本强>
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.peopleList = [{
id: 5,
name:"Raman"
},
{
id: 7,
name:"Komal"
}];
console.log($scope.peopleList[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
</div>