无法访问angularjs数组中的json数据

时间:2017-03-26 15:01:26

标签: javascript angularjs json angular-http

我已经成功返回了一个json对象,该对象具有来自数据库的查询结果。我无法逐个访问返回的json。

以下是console.log显示的内容: enter image description here

角度代码:

$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

访问它以进行打印

2 个答案:

答案 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>