2015-04-24 66 views
0

我正在努力使我的指令充滿來自api的數據。如果我用普通的json提供它,它工作得很好,但是如果我使用http get get blanks(響應在控制檯中很好)。

這種情況下的最佳做法是什麼。我發現了一些關於手錶的東西,但看起來很骯髒,不是嗎?還不太清楚它如何堅持我的方案..

angular.module('contestantList', []) 
    .directive('cContestantList', function() { 
    return { 
     scope: {}, 
     templateUrl: '/app/themes/pomgallery/contestant_list.html', 
     replace: true, 
     controller: 'ContestantListCtrl', 
     controllerAs: 'ctrl' 
    }; 
    }) 
    .controller('ContestantListCtrl', function($scope, $http) { 

    $http({ 
     method: 'GET', 
     url: '/wp-json/posts', 
     params: { 
     'filter[posts_per_page]': 3 
     }, 
    }). 
    success(function(data, status, headers, config) { 
     this.contestants = data; /* DOES NOT WORK */ 
    }). 
    error(function(data, status, headers, config) {}); 

    /* WORKS */ 
    //this.contestants = [{ "title": "Nadine Shjölin, Solo Exhibition"},{"title": "Hello world!"}]; 
    }); 

angular.module('PomGallery', ['contestantList']); 
+0

你能粘貼here..there必須有的屬性裏面你加入這個數據,如'響應{「結果」:[{..//your數據}]}' –

回答

2

this沒有控制器的情況下成功回調中(不同範圍)

嘗試在變量存儲第一。

.controller('ContestantListCtrl', function($scope, $http) { 
    var vm = this; // store reference to "this" 
    $http({ 
     method: 'GET', 
     url: '/wp-json/posts', 
     params: { 
     'filter[posts_per_page]': 3 
     }, 
    }). 
    success(function(data, status, headers, config) { 
     vm.contestants = data; 
    })...... 
+0

啊,太好了!似乎有點向後,但因爲它的作品,我很高興:) – INT

+1

是常見的JavaScript範圍問題 – charlietfl