1

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?

1
  • Looks like your data is an array of objects that contain track and album. So, something like would work for your sample: result.data[0].tracks Commented Mar 4, 2015 at 15:30

3 Answers 3

2

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

2 Comments

$http returns a respose object in the .then function, and response.data is the actual data - i.e. the top-level array object above.
@NewDev You are absolutely right, I misread and thought the OP was using .success. My mistake, I will correct.
0

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

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

1 Comment

For some reason using '[0]` throws an error live, but not locally, TypeError: Cannot read property 'id' of undefined
0

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.