[英]How to call function when variable is available in angularjs
In geocodePosition function which generates place_id, which is use by service.getDetails
in same function(geocodePosition). 在geocodePosition函数中生成place_id,由
service.getDetails
在同一函数(geocodePosition)中使用。 But problem is that this code is not stop till get place_id and go to service.getDetails which is using place_id, which is not generated yes. 但问题是这个代码不会停止,直到获取place_id并转到使用place_id的service.getDetails ,这不会生成yes。 So how to wait till place_id is generated.
那么如何等到place_id生成。
function geocodePosition(pos){
geocoder.geocode({ latLng: pos}, function(responses){
$scope.place_id=responses[0].place_id;
console.log('$scope.place_id'+$scope.place_id);
});
var map=$scope.map.control.getGMap();
var service = new google.maps.places.PlacesService(map);
$scope.$watch(function(){
return $scope.place_id
}, function(place_id){
service.getDetails({placeId: place_id}, function(place, status){
console.log('place'+place);
});
});
}//End of geocodePosition
You can $watch
your $scope.place_id
variable and call the getDetails
if changes. 您可以
$watch
$scope.place_id
变量并在更改时调用getDetails
。
$scope.$watch(function() {
return $scope.place_id;
}, function(place_id) {
if (!place_id) {
return;
}
service.getDetails({ placeId: place_id }, function(place, status) {
console.log('place='+place);
});
});
As geocoder.geocode
is asynchronous: Use $q for introcing promises in your code. 由于
geocoder.geocode
是异步的:使用$ Q在你的代码introcing承诺。
For example: 例如:
function geocodePosition(pos){
q = $q.defer;
geocoder.geocode({ latLng: pos}, function(responses){
var place_id=responses[0].place_id;
console.log('$scope.place_id'+$scope.place_id);
q.resolve(place_id);
}
};
geocodePosition(pos).then(function(place_id){
//use it here...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.