Scope variable doesn't set

孤人 提交于 2019-12-13 19:22:48

问题


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;
    });
});


来源:https://stackoverflow.com/questions/34969263/scope-variable-doesnt-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!