2

I have been messing with this for 2 hours, can not find a solution. Below is the chrome dev tools output showing the logs.

(in order)

3 - undefined

1 - check

2 - A Google User

Why is the place variable in my html not being updated to 'A Google User'?

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

myApp.controller('AppCtrl', ['$scope', '$http', '$log',
  function($scope, $http, $log) {

    var request = {
      placeId: 'ChIJX3piIfJ4j4ARXuQlqgn6LaA' //Walmart HQ
    };

    service = new google.maps.places.PlacesService(map);

    service.getDetails(request, function(place, status) {
      $log.log('1 - check');
      $log.log('2 - ' + place.reviews[0].author_name);
      $scope.place = place.reviews[0].author_name;
   });

    $log.log('3 - ' + $scope.place);
  }
]);

<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <title>Place details</title>
  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>

  <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js'></script>

  <script src="app.js"></script>
</head>

<body>
  <div id="map"></div>
  <div ng-controller='AppCtrl'>

    {{ place }}

  </div>
  </div>


</body>

</html>

1 Answer 1

1

google.maps.places.PlacesService is not the built-in async handler, you need to run $scope.$apply after the async call. Use $scope.$apply to update the view:

$scope.$apply(function () {
    $scope.place = place.reviews[0].author_name;
});

Update 1

Check $apply:

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.

Angular performs dirty checking when probable updates happen. XHR calls are not within the range. Angular doesn't update the views unless you ask it to do dirty checking through $apply.

A best practice is: use Angular built-in providers where possible, such as $timeout, $http. Or ng-click, ng-change, etc. These will call $apply implicitly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.