Google places autocomplete with angular js

我只是一个虾纸丫 提交于 2020-01-24 04:58:05

问题


I am trying to make google places autocomplete work with angular js. Here is jsfiddle - Model is not getting updated after'place_change' event. It is getting updated on change of input.

Below is html code - HTML

<body ng-app="mapApp">
    <div ng-controller="MapController">
        <input id="from" type="text" ng-model="user.from" placeholder="Type Address" class="ng-pristine ng-valid" autocomplete="off">
        <input type="hidden" ng-model="user.fromLat">
        <input type="hidden" ng-model="user.fromLng">
            <p>{{user.from}} <br> {{'Latitude : ' + user.fromLat + ', Longitutde : ' + user.fromLng}}</p>
    </div>
</body> 

Java Script

var mapApp = angular.module('mapApp', []);

mapApp.controller('MapController', function ($scope) {
    $scope.user = {'from': '', 'fromLat': '', 'fromLng' : ''};
    var options = {
        componentRestrictions: {country: "in"}
    };
    var inputFrom = document.getElementById('from');
    var autocompleteFrom = new google.maps.places.Autocomplete(inputFrom, options);
    google.maps.event.addListener(autocompleteFrom, 'place_changed', function() {
        var place = autocompleteFrom.getPlace();
        $scope.user.fromLat = place.geometry.location.lat();
        $scope.user.fromLng = place.geometry.location.lng();
        $scope.user.from = place.formatted_address;
    });
});

回答1:


You need to tell angular when the place_change event gets fired so it knows when to update the DOM. You can do that by calling $scope.$apply(). e.g.:

google.maps.event.addListener(autocompleteFrom, 'place_changed', function() {
        var place = autocompleteFrom.getPlace();
        $scope.user.fromLat = place.geometry.location.lat();
        $scope.user.fromLng = place.geometry.location.lng();
        $scope.user.from = place.formatted_address;
        $scope.$apply();
    });


来源:https://stackoverflow.com/questions/24636711/google-places-autocomplete-with-angular-js

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