user2836797
user2836797

Reputation:

$scope is not accessible from callback function after following Google docs

I have followed the Google documentation (scroll down) for bootstrapping AngularJS with Cloud Endpoints. My code looks like this:

index.html

<!DOCTYPE html>
<html ng-app="AnimalsApp">
<head>
<meta charset="UTF-8">
<title>Animal Manager Server</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<script src="js/animal.js"></script>
<script src="https://apis.google.com/js/client.js?onload=init"></script>
</head>
<body>
  <div ng-controller="MainCtrl" class="container">
    {{message}} world
  </div>
</body>
</html>

animal.js

angular.module('AnimalsApp', [])
  .controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
    $scope.message = 'Hello';  
    $window.init = function() {
      $scope.$apply($scope.load_guestbook_lib);
    };
    $scope.load_guestbook_lib = function() {
      gapi.client.load('creatureCloud', 'v1', function() {
        $scope.is_backend_ready = true;
        $scope.message = 'Hello beautiful';  
        console.log('Made it!');
      }, 'http://localhost:8888/_ah/api');
    };
  }]);

function init() {
  window.init();
}

The text Made it! is shown in the console log, demonstrating that the callback was executed. However, setting $scope.is_backend_ready = true has no effect on showing <div id="listResult" ng-controller="MainCtrl" class="container">. This leads me to believe that the $scope object in the callback is not working correctly.

What have I done wrong? Are the Google docs wrong?

Upvotes: 1

Views: 602

Answers (1)

PSL
PSL

Reputation: 123739

Your intention of using $scope.$apply() is correct but it is in the wrong place. You need to do it in the callback not out of it. With the way you have you are executing the function load_guestbook_lib and then performing a digest cycle. Since the gapi.client.load function is async it runs later and no digest happens as it happens out of angular context.

Try:

$window.init = function() {
  $scope.load_guestbook_lib(); //Just invoke the function
};
$scope.load_guestbook_lib = function() {
  gapi.client.load('creatureCloud', 'v1', function() {
    $scope.is_backend_ready = true;
    $scope.message = 'Hello cats';  
    console.log('Made it!');
    $scope.$apply(); //<-- Apply here
  }, 'http://localhost:8888/_ah/api');
};

Upvotes: 4

Related Questions