Struggling to retrieve accurate information from JSON file in AngularJS

Having some issues with my initial AngularJS project. I am utilizing a yeoman generator and trying to fetch data from a JSON file to check the length of an array containing objects.

This is contents of my data.json file:

{"persons":[
    {  
         "firstname":"Christian",
         "lastname":"Bower",
         "age":21
      },
      {  
         "firstname":"Anthony",
         "lastname":"Martial",
         "age":25
      }
]}

Here's a snippet from my angular controller:

'use strict';

        /**
         * @ngdoc function
         * @name webdevApp.controller:DataTableCtrl
         * @description
         * # DataTableCtrl
         * Controller of the webdevApp
         */
        angular.module('webdevApp')
          .controller('DataTableCtrl', function ($scope, $http) {
            this.awesomeThings = [
              'HTML5 Boilerplate',
              'AngularJS',
              'Karma'
            ];


            $http.get('../data.json').success(function(data){
                $scope.Data = data;
                $scope.namePerson = $scope.Data.persons[0].firstname;
            });

         console.log($scope.namePerson);
         console.log($scope.Data.length);
      });

Console output:

1) undefined

2) TypeError: Cannot read property 'length' of undefined at new

The next issue - How can I achieve the desired effect shown below (array with objects)?

$scope.persons = [
    { 
        "firstname": "christian", 
        "lastname": "bower", 
        "age": 21
    },
    { 
        "firstname": "anthony1", 
        "lastname": "martial", 
        "age": 25 
    }];

Answer №1

When making an asynchronous call with <code>$http.get
, it is important to handle the results within the success function:

       $http.get('../data.json').success(function(data){
            $scope.Data = data;
            $scope.namePerson = $scope.Data.persons[0].firstname;

            console.log($scope.namePerson);
            console.log($scope.Data.length);

            $scope.persons = data.persons; // access your persons array
        });

Answer №2

Remember, the $http.get call operates asynchronously!

Make sure to place your logs within the success function.

$http.get('../data.json').success(function(data){
    $scope.Data = data;
    $scope.namePerson = $scope.Data.persons[0].firstname;

    //assign persons in scope
    $scope.persons = data.persons;

    //logs
    console.log($scope.namePerson);
    console.log($scope.Data.length);
});

It's worth noting that I believe it's best practice to only assign data or even just persons in scope as you can access everything you need from there. Excess variables in scope may lead to unnecessary complexity.

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

json Exploring Input/Output Operations in SQL Server

When I insert serialized data into my SQL server, for example: "{\"Array\":\"Service\",\"Setting\":[{\"Id\":1},{\"Id\":2},{\"Id\":3},{\"Id\":4}]}" I then retrieve this value from the d ...

Anonymous self-executing functions with parameters from an external scope

Recently, I stumbled upon the code snippet below while following a tutorial. const increment = (function(){ return function incrementbytwo (number){ return number+2; } })(); console.log(increment(1)); The result of the code above is 3. ...

What is the best way to add borders to the cities on interactive SVG maps?

I'm currently developing Interactive SVG Maps showcasing Turkey. The map consists of 81 cities, each represented by <g> elements, and their respective districts, created as child elements within the city elements. It's worth noting that the ...

What causes a $watch to be triggered by binding even when there is no change in the data?

Currently, I am working with an entity that is being edited by the user. To ensure that custom validation is triggered each time the entity is modified, I have implemented the following code snippet: // validate the position if anything has changed $scope ...

Ways to compare two arrays based on a specific field using JavaScript

I have two arrays, known as array 'a' and array 'b'. var a = [ [1,'jake','abc',0 ], ['r', 'jenny','dbf',0] , ['r', 'white','dbf',0] ] var b = [ ['s&ap ...

Using React Native with TypeScript to Select the Parent and Child Checkboxes within a FlatList

My objective is to ensure that when a user selects a checkbox for one of the parent items ('Non Veg Biryanis', 'Pizzas', 'Drinks', 'Desserts') in the flatlist, all corresponding child items should also be selected au ...

"Node.js and Webpack - the dynamic duo of

Have you ever wondered why we need to use webpack and npm to install node for JavaScript, when we can simply run JavaScript code directly in our browser? And how exactly do we go about implementing webpack into our project files? ...

Encountering difficulties while trying to include js-search in a Vue.js component

My current challenge involves importing the js-search npm module into a Vue component. However, whenever I attempt to do so using: import JsSearch from 'js-search' The subsequent console.log(JsSearch) statement returns undefined. To further in ...

Browsing through tabs to locate specific text

Currently, I am developing a feature for a Chrome extension and I could use some assistance in debugging. The feature involves retrieving a user's input as a string from a text box on popup.html and then scanning through all the open tabs in the curr ...

Guide to deserializing a collection of interfaces within a child element

My ASP.NET MVC2 application features a complex object structure as outlined below: public class IDealer { string Name { get; set; } List<IVehicle> Vehicles { get; set; } } public class DealerImpl { public string Name { get; set; } public Li ...

An error occurs when trying to access data from the cities of a specific state. The error message reads: "Unable to retrieve property 'data

An error occured: Cannot read property 'data' of undefined at Object.city The issue I am facing is that I am dynamically calling the state parameter. When I use cities.UP.data, it displays the correct result. However, when I try to add cities.st ...

preserve functionality when switching between pages

I have created two simple functions that can change the background color of the body. <script type="text/javascript"> function switchBackground(color){ document.body.bgColor=color; } </script> I am using links with onclick to execute thes ...

Sending information from one page to another and then sending it once more

I am currently utilizing the following code to submit a form's data to : <script type="text/javascript"> $(document).ready(function(){ $("#textnextofkin").validate({ debug: false, rules: { ...

"Image Reactor: Unleashing the Power

I'm struggling to understand why my relative path image loading isn't functioning correctly. The assets are located within the src folder in my working directory, but for some reason, they're not displaying as expected. When I directly impo ...

xhttp.load path for server-side module

I'm currently working on developing a node package and in my JavaScript code, I have the following: const calcHtml = './calc.html'; const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4) { ...

`The console is displaying incorrect results when returning a JSON object`

Need to extract the full address as well as the lat and long values from the provided JSON data. var place = { "address_components": [{ "long_name": "17", "short_name": "17", "types": [ "street_number" ] }, ... ...

How to access ng-model value within ng-repeat with ng-change

Hey everyone, I'm new to working with Angular and I've been facing some issues trying to retrieve the value of ng-model from within ng-repeat. Currently, I have an array of users and my goal is to assign different access levels to each user use ...

Getting rid of a texture in three.js

I am attempting to deallocate a texture once it has been loaded in three.js. The texture is loaded using var tex = THREE.ImageUtils.loadTexture("image.png"); and it is being displayed correctly. However, when I attempt to use: tex.dispose(); I consist ...

transmit data using JSON through a multipart upload

I need help with uploading a video file and JSON data via a REST API using Python's requests library. Below is a sample cURL command for the request. curl -XPOST -i "https://io.cimediacloud.com/upload" \ -H "Authorization: Bearer ACCESS_TOKEN" ...

Is there a way to gracefully deserialize a nested timespan property using System.Text.Json?

I am currently working on deserializing JSON data using System.Text.Json and converters. After examining the raw HTTP response content, it appears that the JSON data is valid. The converter responsible for deserializing the content into the specified obse ...