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

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

本文关键字:回调 访问 函数 文档 scope Google      更新时间:2023-09-26

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

索引.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>

动物.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对象无法正常工作。

我做错了什么?谷歌文档错了吗?

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

尝试:

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