我嘗試從服務中獲取來自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;
}
哦,請用'con替換'alert' sole.log' –
替換爲consloe.log。 (警報顯示呼叫方法序列) – Naresh