NG模型仅在使用谷歌地图自动完成时单击后更新输入

ng model only updating input after click when using google maps autocomplete

本文关键字:完成时 单击 输入 更新 谷歌地图 模型 NG      更新时间:2023-09-26

我收到了来自 rest API 的谷歌地图地点 ID。然后我使用谷歌地图 api 来获取这样的地点对象:

var geocoder = new google.maps.Geocoder;
        geocoder.geocode({
            'placeId': data.city
        }, function(results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    $scope.place = results[0];
                } else {
                    window.alert('No results found');
                }
            } else {
                window.alert('Geocoder failed due to: ' + status);
            }
        });

我正在将结果写入我在前端使用的范围变量中,如下所示:

<label><span>Stadt</span><input type="text" g-places-autocomplete ng-model="place.formatted_address" name="city" class="f-trans"/></label>

我正在使用 github 的 kuhnza/angular-google-places-autocomplete 来实现自动完成功能。不知何故,现在我遇到了一个问题,当范围变量由顶部的函数设置时,它不会更新输入。只有当我在输入字段内部再次单击输入字段外部时,它才会更新并且自动完成功能正在运行而没有任何问题。它与我正在使用的"kuhnza/angular-google-places-autocomplete"标签无关,因为如果我删除它,它仍然不起作用。

您正在更新角度之外的模型。因此,在您与 angular 交互之前,它不会意识到值已更新。最后,我检查了确保更新在角度摘要中的最简单方法是将其包装在$timeout中(确保也注入它)。

if (results[0]) {
  $timeout(function() {
    $scope.place = results[0];
  });
} else {
  window.alert('No results found');
}