关注Google文档后,无法通过回调函数访问$ scope

时间:2015-01-17 03:29:33

标签: javascript angularjs google-cloud-endpoints

我已跟随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文档是错误的吗?

1 个答案:

答案 0 :(得分:4)

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