kuhnza / angular-google-places-autocomplete

Pure AngularJS directive for Google Places Autocomplete
MIT License
257 stars 187 forks source link

$digest errors when typing/deleting #94

Open alastair-todd opened 8 years ago

alastair-todd commented 8 years ago

Happens a lot but inconsistently when deleting text in the input box:

angular.js:13550 Error: [$rootScope:inprog] $apply already in progress http://errors.angularjs.org/1.5.5/$rootScope/inprog?p0=%24apply at angular.js:68 at beginPhase (angular.js:17587) at Scope.$digest (angular.js:17025) at Scope.$apply (angular.js:17337) at autocomplete.js:188 at m$ (places_impl.js:9) at l$.getPlacePredictions (placesimpl.js:25) at . (js?libraries=places:131) at Object..M (js?libraries=places:47) at qz.getPlacePredictions (js?libraries=places:131)

andrehsmendes commented 8 years ago

Happening every time when changing to another view.

angular.min.js:114 Error: [$rootScope:inprog] http://errors.angularjs.org/1.5.0/$rootScope/inprog?p0=%24digest at Error (native) at http://localhost/socialmarkt/js/angular.min.js:6:416 at r (http://localhost/socialmarkt/js/angular.min.js:133:351) at m.$apply (http://localhost/socialmarkt/js/angular.min.js:141:252) at a.onresize (http://localhost/socialmarkt/vendor/angular-google-places/dist/autocomplete.min.js:1:4949) at Object.trigger (http://localhost/socialmarkt/js/jquery-2.1.4.min.js:3:5636) at http://localhost/socialmarkt/js/jquery-2.1.4.min.js:3:11542 at Function.each (http://localhost/socialmarkt/js/jquery-2.1.4.min.js:2:2882) at n.each (http://localhost/socialmarkt/js/jquery-2.1.4.min.js:2:847) at n.trigger (http://localhost/socialmarkt/js/jquery-2.1.4.min.js:3:11518)

alastair-todd commented 8 years ago

Here's a fix on the code, based on the best non-answer on this SO: http://stackoverflow.com/questions/12729122/angularjs-prevent-error-digest-already-in-progress-when-calling-scope-apply

The promise after the call to the google service needs wrapping in a timeout to ensure it gets called without throwin an $apply already in progress error:

autocompleteService.getPlacePredictions(request, function(predictions, status) {
     $timeout(function() {

         $scope.$apply(function() {

             var customPlacePredictions;

             clearPredictions();

             if ($scope.customPlaces) {
                 customPlacePredictions = getCustomPlacePredictions($scope.query);
                 $scope.predictions.push.apply($scope.predictions, customPlacePredictions);
             }

             if (status == google.maps.places.PlacesServiceStatus.OK) {
                 $scope.predictions.push.apply($scope.predictions, predictions);
             }

             if ($scope.predictions.length > 5) {
                 $scope.predictions.length = 5; // trim predictions down to size
             }
         });
     });
 });