0

我正在使用angularjs get方法從服務器獲取提要數組。這是我的控制器代碼。Angularjs調用同步

$scope.feeds = new Array(); 

    $scope.feeds = FeedService.getFeeds(); 
    console.debug("in controller : "+$scope.feeds); 

和我FeedService代碼firbug控制檯我爲$scope.feeds越來越undefined而在FeedbackService它打印JSON對象是

getFeeds : function(){ 
      $http.get('/app/get').success(function(response){ 
           console.debug(response);      
           return response; 

      }).error(function(){ 
       console.debug("failed"); 
      }); 
     } 

。我知道我得到undefined,因爲代碼是同步的。我能做些什麼來處理這個問題。我的html是

<div ng-repeat = "feed in feeds"> 
    <feed feed-text={{feed.feedText}} feed-user={{feed.user}}></feed> 
</div> 

我沒有打印任何東西在頁面上。

回答

0

一種方法是從你的$http調用返回一個承諾,然後在你的控制器解決它和scope屬性綁定到響應:

getFeeds : function(){ 
     return $http.get('/app/get'); 
    } 

// in controller: 

Feedservice.getFeeds().then(function(promise){ 
    $scope.feeds = promise.data; 
}) 
+0

三江源這麼多,它的工作 – Shahzeb

+2

不客氣。我建議http://egghead.io作爲關於angular的主題的視頻教程的一個很好的資源。他解釋了承諾的概念,比我所能做的更好:) – Sprottenwels

+0

謝謝,我會看看這些教程。 – Shahzeb