范围变量未设置

时间:2016-01-23 21:46:15

标签: angularjs angularjs-directive google-places-api

我收到地址自动填充的指令并获取地点信息。此外,我添加了一个代码,用于获取城市ID和代码在我过去的一个项目中工作,但现在不工作(代码中的data [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();
          });
      }
  };
});

1 个答案:

答案 0 :(得分:1)

因为,行scope.form.object.localityId = data[0].place_id;是一个异步调用的回调函数。含义,范围。$ scope()在范围内设置localityId之前调用。因此,您还需要在设置localityId后触发摘要。

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