-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

3
  • 1
    That's because your are doing an asynchronous call, try with console.log, but inside then. Commented Mar 26, 2017 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 Commented Mar 26, 2017 at 15:16
  • Possible duplicate of How do I return the response from an asynchronous call? Commented Mar 26, 2017 at 17:16

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.