XingD123 XingD123 - 6 months ago 20
AngularJS Question

Can't get proper data from json file AngularJS

I have problem with my first AngularJS app. I'm using yeoman generator. I need to get data from json file and check the length of array with objects.

My data.json file:

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


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


Next question is - How can I achieve effect as below (array with objects)?

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

Answer

$http.get is an asyncronous call so you have to output its results in the success function like this:

       $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; // get your persons array
        });