我有一个角度指令,用于侦听谷歌地方'place_changed'事件。代码在桌面浏览器中运行良好。
但是,它不适用于iOS7中的移动Safari(未测试旧版本)。点击一个位置似乎没有触发place_changed事件,并且输入字段没有填充位置值。
是否还有其他一些我应该触发的事件,在听?
angular.module('app').directive('googlePlace', function (Location) {
return {
restrict: 'A',
require: 'ngModel',
link: function ($scope, element, attributes, model) {
var autocomplete = new google.maps.places.Autocomplete(element[0], {types: ['(cities)']});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
if (autocomplete.getPlace()){
var googlePlace = autocomplete.getPlace();
$scope.googlePlace = googlePlace;
Location.setGooglePlace(googlePlace);
var location = googlePlace.address_components[0].long_name + ', ';
if (googlePlace.address_components.length === 2) {
location = location + googlePlace.address_components[1].long_name;
} else if (googlePlace.address_components.length === 3) {
location = location + googlePlace.address_components[2].long_name;
} else if (googlePlace.address_components[3].short_name === 'US') {
location = location + googlePlace.address_components[2].short_name;
} else {
location = location + googlePlace.address_components[3].long_name;
}
$scope.displayLocation = location;
$scope.$apply(function () {
setTimeout(function(){
model.$setViewValue($scope.displayLocation);
model.$setValidity(element.name, true);
element.val($scope.displayLocation);
}, 100);
});
} else {
$scope.googlePlace = null;
$scope.displayLocation = null;
model.$setViewValue($scope.displayLocation);
model.$setValidity(element.name, true);
element.val($scope.displayLocation);
}
});
element.on('blur', function () {
setTimeout(function(){
if (attributes.required && !$scope.googlePlace){
model.$setValidity(element.name, false);
} else if (element.val() && !$scope.googlePlace){
model.$setValidity(element.name, false);
} else if (!element.val()){
Location.setGooglePlace(null);
model.$setValidity(element.name, true);
} else{
model.$setViewValue($scope.displayLocation);
model.$setValidity(element.name, true);
element.val($scope.displayLocation);
}
}, 300); // this seems to matter even though 0
});
element.on('keypress', function (e) {
$scope.googlePlace = null;
Location.setGooglePlace(null);
if (e.which === 13) {
google.maps.event.trigger(autocomplete, 'place_changed');
}
});
}
};
});