在angularJs中读取json数据时遇到麻烦

时间:2015-04-23 11:07:10

标签: javascript json angularjs

我正在尝试读取一个json文件,其中包含歌曲列表和图像的URL

{"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"
    }
]}

但基本问题是当我使用$ http.get()时,它会读取json,但我无法将其分配给angularJS对象,这里是我的angularJS代码

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);
                }

        }]);

“长度”字段将结果显示为5,但即使是一次,我的for循环也不会运行..

1 个答案:

答案 0 :(得分:0)

错误次数

  1. 您不应将$scope传递给$http.get
  2. 你不能直接在ajax之外得到$scope.songList值,这个值是通过ajax调用填充的,所以你需要在ajax成功中运行循环
  3. <强>代码

    $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);
      }
    });