David
David

Reputation: 1191

Access nested JSON object in AngularJS controller

I am new to AngularJS and trying to create a $scope for tracks for later usage

data.json (sample):

[
{
    "album": "Album name",
    "tracks": [
        {
            "id": "1",
            "title": "songtitle1",
            "lyric": "lyrics1"
        },
        {
            "id": "2",
            "title": "songtitle2",
            "lyric": "lyrics2"
        }
    ]
}
]

Controller

app.controller('lyricsCtrl', function($scope, $http) {
$http.get('data.json')
    .then(function(result) {
        $scope.albums = result.data;
        $scope.tracks = result.data.tracks;

        console.log($scope.tracks);  //Undefined...
    });
});

Why is $scope.tracks undefined?

Upvotes: 1

Views: 11880

Answers (3)

jnthnjns
jnthnjns

Reputation: 8925

If your json file is as is:

[
    {
        "album": "Album name",
        "tracks": [
            {
                "id": "1",
                "title": "songtitle1",
                "lyric": "lyrics1"
            },
            {
                "id": "2",
                "title": "songtitle2",
                "lyric": "lyrics2"
            }
        ]
    }
]

We have a response of:

data: Array[1]
    0: Object
        album: "Album name"
        tracks: Array[2]

Since data is returned as an array you would handle like any other javascript array and access by index, so you could do a loop or if you know only 1 result is going to be returned you could use the zero index:

$http.get('data.json').then(function(result) {
    console.log(result);
    // Assign variables
    $scope.album = result.data[0].album;
    $scope.tracks = result.data[0].tracks;
    for (var i = 0, l = $scope.tracks.length; i < l; i++) {
        console.log($scope.tracks[i].title);
    }
});

Upvotes: 2

Shashi
Shashi

Reputation: 1182

It should be result.data[0].tracks as data is an array

$scope.tracks = result.data[0].tracks;

Upvotes: 0

squiroid
squiroid

Reputation: 14027

result.data is an array,So you must have to use index to access its child like:-

$scope.tracks = result.data[0].tracks;

Upvotes: 0

Related Questions