访问AngularJS控制器中的嵌套JSON对象

时间:2015-03-04 15:22:57

标签: json angularjs object controller

我是AngularJS的新手并尝试为$scope创建tracks以供日后使用

data.json(样本):

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

控制器

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

为什么$scope.tracks未定义?

3 个答案:

答案 0 :(得分:2)

如果你的json文件是这样的:

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

我们的答复是:

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

由于data作为数组返回,您将像任何其他javascript数组一样处理并按索引访问,因此您可以执行循环,或者如果您只知道将返回1个结果,则可以使用零指数:

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

答案 1 :(得分:0)

result.data是一个数组,所以你必须使用索引来访问它的子类,如: -

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

答案 2 :(得分:0)

它应该是result.data [0] .tracks,因为数据是一个数组

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