0

I am trying to read a json file which contains the list of songs and a url to the image

{"songs" : [
{
    "SongName" : "Broken Dreams",
    "image" : "img/browser.svg"
},
{
    "SongName" : "My heart goes on",
    "image" : "img/browser.svg"
},
{
    "SongName" : "Summer of 69",
    "image" : "img/browser.svg"
},
{
    "SongName" : "Broken Hearted Girl",
    "image" : "img/browser.svg"
},
{
    "SongName" : "American idiot",
        "image" : "img/browser.svg"
    }
]}

but the basic issue is when I use the $http.get(), it reads the json but I am not able to assign it to the angularJS object, here is my angularJS code

var app = angular.module('TheSlideShow', []);
        app.controller('mainController', ['$scope', '$http', function($scope, $http){

            $scope.test = "this is a test string";
            $scope.songList = {};

                $http.get("Data/SongList.json", ['$scope']).success(function(List){ $scope.songList  = List.songs;  console.log("The Length : " + $scope.songList.length);});

            for(var i = 0; i< $scope.length; i++)
                {
                    console.log("loop number" + i);
                }

        }]);

The Length field gives the result as 5 but my for loop does not run even for a single time..

Pragam Shrivastava
  • 1,428
  • 3
  • 13
  • 20

1 Answers1

0

Number of mistakes

  1. You should not pass $scope to $http.get
  2. You can not get $scope.songList value outside ajax directictly, the value is getting populated through ajax call, so you need to run for loop inside ajax success

Code

$http.get("Data/SongList.json").success(function(List){ 
  $scope.songList  = List.songs;  
  console.log("The Length : " + $scope.songList.length);
  for(var i = 0; i< $scope.songList.length; i++)
  {
     console.log("loop number" + i);
  }
});
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • 1
    Hey thanks for reminding me about the $scope variable, I was using the hit and trial method and forgot to remove it. I want to use the data from the json into another function is there any other way to do it? I mean how I could pass my song list to the different function? – Pragam Shrivastava Apr 23 '15 at 12:00
  • does that javascript function inside inside controller? – Pankaj Parkar Apr 23 '15 at 12:03
  • Yes! that function would be inside the same controller! – Pragam Shrivastava Apr 23 '15 at 12:28
  • you could easily pass it as param like `$scope.someFunction($scope.songList)` & the function would be `$scope.someFunction = function(songs){ //you could songs here }` – Pankaj Parkar Apr 23 '15 at 12:35