AngularJS中的$ scope在ng-repeat中不返回任何内容

时间:2014-04-17 12:34:28

标签: javascript angularjs

我正在尝试返回一个对象,我在一个forEach循环中填充了一个来自控制器的angulars $ scope,但是当我尝试用ng-repeat循环它时,我得不到任何结果。

当我在console.log中获取预期结果的对象时

enter image description here

但是当我尝试用$ scope返回它并用ng-repeat显示它时,我得不到任何结果。

这是我的控制器

myAppControllers.controller('musicCtrl', ['$scope', '$http', function($scope, $http) {

var i = 0,
    playlists = {};

// Get the playlists from soundcloud
$http({ method: 'GET', url: 'http://api.soundcloud.com/users/gimle-sound-tjek/playlists.json?client_id=c2dfe07de1d18d689516884ce22b7aae' }).
    success(function(data) {
        data.forEach(function() {

            // Populate the object
            playlists[i] = {
                "title" : data[i].title,
                "permalink": data[i].permalink,
                "genre": data[i].genre
            }

            i++;
        });

        console.log(playlists);
        $scope.playlists;
    }).
    error(function() {
        $scope.playlists = '';
    });
}]);

我的ng-repeat看起来像这样

<div ng-repeat="playlist in playlists">
<h3>{{ playlist.title }}</h3>
...

我希望这与我使用$ scope.playlists发回对象的方式有关?

2 个答案:

答案 0 :(得分:1)

首先,可以使用push代替这个i++的乐趣。

您可以将这些播放列表条目推送到范围之外的播放列表变量中。

myAppControllers.controller('musicCtrl', ['$scope', '$http', function($scope, $http) {
    $scope.playlists= [];

// Get the playlists from soundcloud
$http({ method: 'GET', url: 'http://api.soundcloud.com/users/gimle-sound-tjek/playlists.json?client_id=c2dfe07de1d18d689516884ce22b7aae' }).
    success(function(data) {
        data.forEach(function(entry) {    
            // Populate the object
            $scope.playlists.push({
                "title" : entry.title,
                "permalink": entry.permalink,
                "genre": entry.genre
            });
            //OR: $scope.playlists.push(entry);
        });
    }).
    error(function() {
        $scope.playlists = '';
    });
}]);

答案 1 :(得分:0)

如果您尝试$scope.playlists = []而不是var playlist = {}

,该怎么办?