繁体   English   中英

如何在angularjs中提供变量时调用函数

[英]How to call function when variable is available in angularjs

geocodePosition函数中生成place_id,由service.getDetails在同一函数(geocodePosition)中使用。 但问题是这个代码不会停止,直到获取place_id并转到使用place_id的service.getDetails ,这不会生成yes。 那么如何等到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

您可以$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);
  });
});

由于geocoder.geocode是异步的:使用$ Q在你的代码introcing承诺。

例如:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM