【发布时间】:2014-01-19 22:50:05
【问题描述】:
我尝试通过服务的 http 调用获取数据,并将服务的返回数据分配给控制器的变量 $scope。 fusionJsonObj 并最终将此数据传递给指令,使其在指令范围内可用以进行进一步处理。
问题:
在 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;
}
【问题讨论】:
-
哦,请将
alert替换为console.log -
将变更替换为 consloe.log。 (警报是显示调用方法序列)
标签: angularjs