-2

I've successfully returned a json object which has query results from database. I'm unable to access the returned json one by one.

Here's what the console.log shows: enter image description here

Angular code:

$scope.peopleList=[];
            $http.get("http://localhost/project/public/people_names").then(function(response) {
                $scope.peopleList.push(response.data);
            });
            console.log($scope.peopleList);

if I use console.log($scope.peopleList[0]);, it says undefined. How do I access it to print it using ng-repeat

Jaskaran Singh Puri
  • 729
  • 2
  • 11
  • 37
  • 1
    That's because your are doing an asynchronous call, try with `console.log`, but inside **then**. – Hosar Mar 26 '17 at 15:05
  • 1
    Instead of pushing just assign the data prop in response object to peopleList. You can then loop over that easily with `ng-repeat` – Umair Sarfraz Mar 26 '17 at 15:16
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – georgeawg Mar 26 '17 at 17:16

2 Answers2

1

Try below code :

$scope.peopleList=[];
$http.get("http://localhost/project/public/people_names")
  .then(function(response) {
     $scope.peopleList = response.data;
     console.log($scope.peopleList);
  });

And use like below with ng-repeat

<div ng-repeat='person in peopleList track by person.id'>
  ....
</div>
Abhishek
  • 1,477
  • 1
  • 10
  • 18
0

Some observations :

  • As response.data is already an array of objects. So, no need to push it again into the different array.
  • You can directly use $scope.peopleList = response.data instead of $scope.peopleList.push(response.data)

Now, if you try to access the first object from an array you can use console.log($scope.peopleList[0]) it will provide you the expected results.

DEMO

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>
Debug Diva
  • 26,058
  • 13
  • 70
  • 123