将服务数据保存到控制器的全局变量中
Saving Service Data To Global Variable in Controller
我无法在位置内更新geodata数组。成功的功能。console.log在函数内部打印JSON对象,但在函数外部未定义。
我想在函数调用之外访问geodata数组内容。任何代码片段都会有帮助。
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);
});
}]);
因为位置。成功是异步的,在调用这个方法后,它移动到console.log(geodata),它将打印空数组而不是null。您必须等待拥有数据的响应。
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); //You can receive here data
});
// console.log(geodata); Because places.success is asycnronous, its the empty array not null
}]);
假设有一个指令(例如my-marker)在地图上显示地理位置,您可以在模板html中使用ng-repeat来运行geodata变量。因此,您应该在控制器范围内定义它。
控制器代码片段
$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>
注意:我已经根据你的指示做出了陈述性的假设。
在您的服务中保存数据(来自您的评论),如下所示:
app.service('places', ['$http', function($http) {
this.dataFromService = [];
this.getData = function(){
return $http.jsonp('en.wikipedia.org/w/…') .success(function(data) {
this.dataFromService = data; });
}
}
]);
然后在你的控制器中调用服务,然后在promise被解析后使用.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
相关文章:
- 全局变量和全局对象的属性之间有什么区别吗
- delete关键字在全局变量上的不同行为
- 在javascript函数中设置全局变量
- 如何将getJson的响应保存在全局变量中
- 从Javascript方法返回全局变量
- AngularJS中的封装窗口全局变量
- javascript隐式全局变量
- 如何从onclick函数设置全局变量并将其传递给另一个JS文件
- 如何使全局变量仅特定于该文件
- 在page.open()-PhantomJS中无法访问全局变量
- 使用全局变量来存储数字(JavaScript)
- 如何将变量声明为全局变量
- 在节点中创建文件全局变量
- 如何从jQuery设置控制器或全局变量的属性
- 将全局变量从控制器调用到HTML视图AngularJS
- NodeJS与AngularJS,所需的HTML文件不是跨控制器的数据绑定全局变量
- 如何使用函数将值更改为作用域中的全局变量?(“控制器”)
- 将服务数据保存到控制器的全局变量中
- Ionic/Angularjs 将控制器更改为全局变量
- 运行和控制器之间的全局变量