范围变量未设置 [英] Scope variable doesn't set

查看:33
本文介绍了范围变量未设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了地址自动完成指令和地点信息.我还添加了一个用于获取城市 ID 的代码,该代码在我过去的一个项目中工作,但现在不起作用(代码中的 data[0].place_id 具有正确的值,但 scope.form.object.localityId 为空函数外.

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... 在指令的父控制器中声明,其他变量填充正确

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

推荐答案

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

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

这篇关于范围变量未设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆