2014-01-19 88 views
0

我嘗試從服務中獲取來自via http調用的數據,並將服務中的返回數據分配給控制器的變量$ scope。 fusionJsonObj並最終將這些數據傳遞給指令,使其在指令範圍內可用於進一步處理。AngularJS在完成服務http調用之前加載指令

問題:

之前HTTP調用獲取數據,並將其分配到控制器$ scope.fusionJsonObj,它說幹就幹,加載指令(此時指令沒有與$ scope.fusionJsonObj作爲承諾的相關數據。該服務沒有從服務器的HTTP調用返回的數據

總之,請大家幫我裝HTTP服務,並承諾在那裏裝載指令之前分配的HTTP數據到控制器$ scope.fusionJsonObj

Plunker鏈接: http://plnkr.co/edit/xGchsnw2u9LremFATfvY?p=preview

控制器如下:

angular.module('FundooDirectiveTutorial', []) 
     .controller('FundooCtrl', function($scope, readFusionTblService, $window) { 
      $scope.rating = 3; //total no of the column 
     $scope.listItemIndex=2; //no of column-1  
     alert('## in the Controller - and calling service method on http call'); 

     var promise = readFusionTblService.getFusionData(); 
     alert('## in the Controller - and calling promise'); 

     promise.then(
        function(dataReturn){ 
         alert('## in the Controller - with promise execution');  
         $scope.fusionJsonObj = dataReturn; 

服務如下:

.service('readFusionTblService', function($http, $q){ 



     alert("### in the Service "); 

     this.getFusionData = function(){ 
          var deferred = $q.defer(); 
          var urlQuery = "https://www.googleapis.com/fusiontables/v1/query?sql=SELECT%20*%20FROM%201n-NpyEkVKBOLSn_yE2LPL5Tk9K79saDkpKCrF00%20WHERE%20country='Sweden'%20AND%20type='glass'%20ORDER%20BY%20ST_DISTANCE(ComputedAddress,LATLNG(42,-83))%20LIMIT%2025&key=AIzaSyBqKyD7u_2CwBMQ3c9qAeMDTJaQIjYlgJo"; 

          alert("### in the Service - before http call");       
          $http.get(urlQuery).success(function(data, status) { 
            alert("### in the Service - After http call ####");         
            deferred.resolve(data); 
           }).error(function(data, status) { 
            deferred.reject(data); 
           });        
          return deferred.promise; 
     } 
+0

哦,請用'con替換'alert' sole.log' –

+0

替換爲consloe.log。 (警報顯示呼叫方法序列) – Naresh

回答

0

你的一些指令功能取決於promisepromise.then總是回報另一個承諾。保持新的承諾,並通過該指令像

var newPromise = promise.then(...); 
$scope.ratingConfig = { 
    myPromise: newPromise 
}; 

HTML傳似

<div fundoo-rating rating-config="ratingConfig" row-item-index="listItemIndex" rating-value="rating" on-rating-selected="saveRatingToServer(rating, ratingTextVal)" item-data="billTblModel" ></div> 

在指令中的承諾,該指令包裹承諾依賴像

scope.ratingConfig.myPromise.then(function() {/*promise depended code*/}); 

功能檢查更新plunker

+0

Reza謝謝答覆。成爲新寵需要你的幫助。 1)在加載mainPage(id =「mainPageId」)之前,如何從$ scope.fusionJsonObj填充「rowDataArray」(現在硬編碼)。 2)同樣在第二頁(id =「dashBoardPageId」),如何從$ scope.fusionJsonObj填充「billTblModel」(現在硬編碼)。 簡而言之$ scope.fusionJsonObj將是一種全局數據(通過來自服務的http調用),然後填充控制器$ scope.variable,它將在頁面加載之前傳遞給指令... – Naresh

+0

Reza,令人驚訝的是newPromise正在工作。如果我想在正確的方向讀取http json數據,請將它存儲到控制器$ scope.fusionJSonObj中,然後執行進一步處理,請指導我。 – Naresh

+0

'$ http'它自己返回'promise',所以當你使用'$ http'時,你不需要'$ q'。如果你的服務器端是'RESTful',你也可以使用帶'$ q'的角度'$ resource',閱讀更多細節http://docs.angularjs.org/api/ngResource.$resource – Reza

相關問題