Scope variable doesn't set

2019-08-11 18:15发布

问题:

I got directive for address autocomplete and get places info. Also I have added a code for getting city id and the code worked in one of my past project, but not working now ( The data[0].place_id in the code have a correct value but scope.form.object.localityId is empty outside the function.

PS scope.form.object... is declared in a parent controller of the directive and other variables are filling correct

.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:

Because, the line scope.form.object.localityId = data[0].place_id; is a callback function that is called asynchronously. Meaning, your scope.$apply() is called before the localityId is set on the scope. So you need to trigger a digest after setting localityId as well.

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