范围变量没有设置

问题描述:

我得到了地址自动完成指令并获取地点信息。此外,我添加了获取城市ID和代码在我以前的项目中工作的代码,但现在无法工作(代码中的数据[0] .place_id具有正确的值,但scope.form.object.localityId为空功能PS scope.form.object之外。范围变量没有设置

...在指令和其他变量的父控制器声明的填充正确

.directive('shAddressPredict', function(){ 
    return { 
     require: 'ngModel', 
     link: function(scope, element, attrs, location) { 
      var options = { 
       types: ['address'], 
      }; 
      scope.gPlace = new google.maps.places.Autocomplete(element[0], options); 
      google.maps.event.addListener(scope.gPlace, 'place_changed', function() { 

       var place = scope.gPlace.getPlace(); 

       scope.form.object.fullAddress = place.name; 
       scope.form.object.placeId = place.place_id; 
       scope.form.object.locality = ''; 
       scope.form.object.localityId = ''; 
       scope.form.object.sublocality_level_1 = ''; 
       scope.form.object.country = ''; 

       var city = ''; 
       angular.forEach(place.address_components, function(data) { 
       scope.form.object[data.types[0]] = data.long_name; 
       if(data.types[0] === 'locality') city += data.long_name + ', '; 
       if(data.types[0] === 'administrative_area_level_1') city += data.short_name + ', '; 
       if(data.types[0] === 'country') city += data.long_name; 
       }); 

       // Geting city id 
       var service = new google.maps.places.AutocompleteService(); 
       service.getPlacePredictions({ 
       input: city, 
       types: ['(cities)'] 
       }, function(data){ 
       scope.form.object.localityId = data[0].place_id; 
       }); 
       scope.$apply(); 
      }); 
     } 
    }; 
}); 

因为,线scope.form.object.localityId = data[0].place_id;是一个回调函数,异步调用,意思是你的作用域,$ apply()在localityId设置在scope上之前调用,所以你需要在设置localityId后触发一个摘要

service.getPlacePredictions({ 
    input: city, 
    types: ['(cities)'] 
}, function(data){ 
    scope.$apply(function() { 
     scope.form.object.localityId = data[0].place_id; 
    }); 
}); 
+0

嗯...是的,对不对)Thx – pavolve