遵循 Google 文档后,无法从回调函数访问 $scope

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

我已按照 Google documentation(向下滚动)使用 Cloud Endpoints 引导 AngularJS。我的代码如下所示:

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();
}

控制台日志中显示文本 Made it!,表明回调已执行。但是,设置 $scope.is_backend_ready = true 对显示 <div id="listResult" ng-controller="MainCtrl" class="container"> 没有影响。这让我相信回调中的 $scope 对象没有正常工作。

我做错了什么? Google 文档有误吗?

您使用$scope.$apply()的意图是正确的,但用错了地方。您需要在回调中执行此操作,而不是在回调中执行。按照你的方式,你正在执行函数 load_guestbook_lib 然后执行摘要循环。由于 gapi.client.load 函数是异步的,它会稍后运行并且不会发生摘要,因为它发生在 angular 上下文之外。

尝试:

$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');
};