将服务数据保存到控制器中的全局变量

时间:2015-09-16 17:36:59

标签: javascript angularjs controllers

我无法更新places.success函数中的地理数据数组。 console.log在函数内部打印JSON对象,但是在函数之外它是未定义的。

我想访问函数调用之外的地理数据数组内容。任何代码片段都会有所帮助。

app.controller('MainController', ['$scope','places', function($scope,places)     {
  $scope.mapCenter = {
  lat: 40.741934,
  lng: -74.004897,
  zoom: 17
  };
  var geodata=new Array();
  places.success(function(data) {
     geodata = data;
     console.log('inside'+geodata); //geodata is having a json value here, returning from data. 
   });
   console.log(geodata); //why geodata is still undefined here, I assigned value 
   }]);

解决了问题:

app.controller('MainController', ['$scope','places', function($scope,places)     {
  $scope.mapCenter = {
      lat: 40.741934,
      lng: -74.004897,
      zoom: 17
    };
  var geodata=new Array();
  var callme=function(data){
    console.log('call'+data)
    $scope.mapMarkers = geodataToMarkers(data)
  }
  places.success(function(data) {
    geodata = data
    console.log('inside'+data); //geodata is having a json value here, returning from data. 
    callme(data);
  });
 }]);

4 个答案:

答案 0 :(得分:0)

因为places.success是asycnronous,在调用此方法后,它将移动到console.log(geodata),它将打印空数组而不是null。您必须等待获得数据的响应。

{{1}}

答案 1 :(得分:0)

假设有一个指令(比如我的标记)在地图上显示地理位置,你可能在模板html中有一个ng-repeat,它将通过地理数据变量运行。因此,您应该在控制器范围内定义它。

控制器代码片段

$scope.geodata = [];
places.success(function (data) {
  $scope.geodata = data; //Note depending on how your promise is resolved you may have to do **data.data** instead of **data**
});

<强>模板

<my-marker ng-repeat="geoDatum in geoData" geo-datum="geoDatum"></my-marker>

注意:我已经针对您的指令做出了明确的假设。

答案 2 :(得分:0)

保存服务中的数据(来自您的评论),如下所示:

app.service('places', ['$http', function($http) {
  this.dataFromService = []; 
  this.getData = function(){
   return $http.jsonp('en.wikipedia.org/w/…') .success(function(data) { 
     this.dataFromService = data; }); 
   }
}
]);

然后在您的控制器中调用该服务,然后使用.then()在解析承诺后访问数据:

app.controller('MainController', ['$scope','places', function($scope,places)     {
  $scope.mapCenter = {
  lat: 40.741934,
  lng: -74.004897,
  zoom: 17
  };
  var geodata=new Array();
  places.getData().$promise.then(function(){
  geodata = this.dataFromService;
  });
  console.log(geodata);
}]);

更多参考:http://weblog.west-wind.com/posts/2014/Oct/24/AngularJs-and-Promises-with-the-http-Service

答案 3 :(得分:-1)

你正在制作一个本地阵列。如果您想要全局,可以使用window.geodata=new Array();

在javascript中,window对象是全局的