Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
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 –  New Dev Mar 4 at 15:30

2 Answers 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);
    }
};
share|improve this answer
    
$http returns a respose object in the .then function, and response.data is the actual data - i.e. the top-level array object above. –  New Dev Mar 4 at 19:25
    
@NewDev You are absolutely right, I misread and thought the OP was using .success. My mistake, I will correct. –  Asok Mar 4 at 19:53

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

$scope.tracks = result.data[0].tracks;
share|improve this answer
    
why negative to it ? –  squiroid Mar 4 at 15:33
2  
sorry for that :-P –  squiroid Mar 4 at 15:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.