Unable to retrieve JSON data from an AngularJS array

I have successfully received a json object containing query results from the database. However, I am currently facing an issue where I am unable to access the returned json data one by one.

When I check the console.log, this is what it shows: https://i.sstatic.net/KHuz0.png

This is my Angular code:

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

Whenever I try to use

console.log($scope.peopleList[0]);
, it keeps showing as undefined. How can I access the data to print it using ng-repeat?

Answer №1

Give this code a shot:

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

Then, implement it like this using ng-repeat

<div ng-repeat='person in peopleList track by person.id'>
  ....
</div>

Answer №2

Upon careful observation :

  • Since response.data is already in the form of an array of objects, there is no requirement to push it into a separate array.
  • You can directly assign
    $scope.peopleList = response.data
    instead of using
    $scope.peopleList.push(response.data)

If you wish to access the first object from the array, you can simply use

console.log($scope.peopleList[0])
to retrieve the desired output.

DEMONSTRATION

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The jQuery dialog dropdown list fails to display on subsequent attempts

I'm currently utilizing a jQuery modal dialog to showcase a drop-down list for users to make selections from. By dynamically populating the drop-downs through adding them to the empty list, I encounter an issue where it only displays the default optio ...

Avoid Empty Values in Converted Array

Eliminating the presence of nils in an array can be achieved using a method outlined in this resource. However, I am curious about the following: 1) What mistake have I made that causes my array to contain nils? 2) How can I AVOID adding nils to my array ...

What may be causing the lag in the translation within ThreeJS?

Just started diving into ThreeJS and discovering its capabilities. Playing around with a simple example of creating a white dot and applying a basic translation. let dotGeometry = new THREE.Geometry(); let dotMaterial = new THREE.PointsMaterial({ size: ...

Is there a more streamlined approach to coding in PHP and jQuery?

My PHP script: <?php $data = file_get_contents('http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/rss.xml'); $xml = simplexml_load_string($data); $data1 = file_get_contents('http://www.skysports.com/rss/0,20514,11661,00.xml ...

Is there a way to configure nodemon to automatically monitor changes in dotenv-flow files?

Files in dotenv-flow can be named with prefixes like: .env, .env.development, .env.development.local, ... If you want your node server to automatically restart when any of these files are updated, you may encounter limitations. Currently, the custom confi ...

Managing AJAX Requests in AngularJS

I am currently developing a Single Page Application where the front end is hosted on one server and the back end is hosted on another. For every add, edit, delete, or fetch operation, I have to make an Ajax request to the Back End. There have been quite ...

Is the performance impacted by using try / catch instead of the `.catch` observable operator when handling XHR requests?

Recently, I encountered an interesting scenario. While evaluating a new project and reviewing the codebase, I noticed that all HTTP requests within the service files were enclosed in a JavaScript try / catch block instead of utilizing the .catch observable ...

What is the best way to implement my function on every value in a JSON file?

I've got a JSON file that contains the following dataset: [{ "planet": "project pluto", "records": [ { "project": "project pluto", "plan": "paper& ...

What does the Problum Unexpected number in JSON at position 13 signify?

I am currently working on coding a WebPage and trying to send JSON data to the front page using AJAX. However, I am encountering an issue where the data is not being received correctly. Upon checking the log messages, I found an error stating "200:undefi ...

Using Python to transform a nested dictionary list into a Pandas Dataframe

I have come across the following dictionary structure test = {'data': [ {'actions': [ {'action_type': 'link_click', 'value': '16'}, {'action_type': 'post_engagement', ...

Tips for adding a JSON object to a JSON array in Python

I am facing a Python file that creates an object for a machine. Here's a sample of it. { "Date/Time": "2019-01-01 8:00:00", "Availability": 68, "Performance": 70, "Quality": 70 } Another Python file is present with JSON data as shown below. Ho ...

It is impossible to resolve Npm vulnerabilities

My journey with learning React began when I decided to create my first app using the command: 'npx create-react-app my-app' However, upon building the app, I encountered a warning in the terminal: 22 vulnerabilities (9 moderate, 13 high) In ...

Angularent ng-include backup plan

When the ng-include directive fails to fetch the resource, I want to display a default HTML content. If the server returns an HTTP status code of 500 or 440 during Angular's attempt to retrieve the include source, the failure is disregarded and no co ...

What is the best way to prevent users from clearing the value attribute of an input element?

Sample Scenario: While a user is entering information into a field, I would like to restrict the ability to delete or clear out the value, such as keeping "Friend" intact. Can this be accomplished using CSS or JavaScript? ...

Assign a variable to the result of ajax that remains unchanged until it is specifically invoked

I am currently working on the final part of my radio script, specifically focusing on the "last song" section. My goal is to retrieve a URL from an external PHP script, play the song, and once the song ends, I want to set a global variable equal to the cur ...

Handling JQuery AJAX HTML responses in the error callback function

var userID = 45; $.ajax({ url :'url', // The URL returns HTML content type: 'POST', dataType: 'json', data :{ID:userID}, success:function(response) ...

Disable the default page scrolling behavior when collapsing an accordion section in Bootstrap 4 framework

Incorporating a Bootstrap 4 accordion with an expanded body section that causes the content below to scroll up when collapsed. To address this issue, attempting to scroll to the top of the clicked header and prevent undesirable scrolling from the collapse ...

Issue with Date.js: Date.monday() function is not functioning as expected

I am attempting to utilize Datejs for some date functions. However, I am encountering issues with functions like Date.march() and Date.monday(). I have downloaded the necessary files from the Datejs website. Upon inspecting with firebug, it appears that my ...

Is it possible for my website to send an email without the need for a script to be executed?

Looking to include a contact page on my website, but struggling with limitations imposed due to hosting on a secure school server that restricts script execution. Wondering if there's a workaround that would allow for email sending on the client side ...

Node.js program closes immediately upon Java startup

I am building a Discord bot that features a Java FXML interface and utilizes a Node.js program to function as an Audio playing bot. However, I am encountering an issue where the process for Node.js closes immediately when opened in Java. The problem arise ...