AngularJS控制器初始化

时间:2013-06-29 17:45:48

标签: angularjs

Angular JS新手:我得到了gapi is not defined,因为在加载API之前调用了sydney.userAuthed。但我不明白为什么在创建控制器时调用方法sydney.auth。我在页面加载时收到错误,没有用户交互。

calling auth api.js:22
ReferenceError: gapi is not defined
    at Object.sydney.userAuthed (http://localhost:8888/js/api.js:36:8)
    at Object.sydney.auth (http://localhost:8888/js/api.js:23:30)
    at new LoginController (http://localhost:8888/js/controllers.js:8:24)
    at invoke (http://localhost:8888/lib/angular/angular.js:2902:28)
    at Object.instantiate (http://localhost:8888/lib/angular/angular.js:2914:23)
    at http://localhost:8888/lib/angular/angular.js:4805:24
    at updateView (http://localhost:8888/lib/angular/angular-ui-router.js:931:30)
    at <error: illegal access>
    at Object.Scope.$broadcast (http://localhost:8888/lib/angular/angular.js:8307:28)
    at $state.transition.resolved.then.$state.transition (http://localhost:8888/lib/angular/angular-ui-router.js:747:20) angular.js:5754
OAuth2 API loaded api.js:13

我将stateui-router定义为:

myapp.config(function($stateProvider, $routeProvider) {

    $stateProvider.state('signin', {
        url : "/", // root route
        views : {
            "signinView" : {
                templateUrl : 'partials/signin.html',
                controller: 'LoginController'
            }
        },
    })

控制器定义为:

function LoginController($scope, $state) {
  $scope.auth = sydney.auth($state);
}

sydney.auth方法用于使用Google APIs Client Library for JavaScript验证用户。

var sydney = sydney || {};

sydney.auth = function($state) {
    console.log("calling auth");
    sydney.signin(false, sydney.userAuthed($state));
}

sydney.signin = function(mode, callback) {
      gapi.auth.authorize({client_id: sydney.CLIENT_ID,
        scope: sydney.SCOPES, immediate: mode,
        response_type: 'token id_token'},
        callback);
      console.log("signin called");
}

sydney.userAuthed = function($state) { 
      var request =
          gapi.client.oauth2.userinfo.get().execute(function(resp) {
        if (!resp.code) {
          var token = gapi.auth.getToken();
          token.access_token = token.id_token;
          gapi.auth.setToken(token);
          // User is signed in, call my Endpoint
          gapi.client.realestate.owner.create().execute(function(resp) {
              alert("Signed In");
              $state.transitionTo("signedin");
            });
        }
      });
    }

修改

正确答案是将$scope.auth定义为函数:

function LoginController($scope, $state) {
  $scope.auth = function() { 
      sydney.auth($state);
  }
}

1 个答案:

答案 0 :(得分:1)

您尝试做的似乎是使您的示波器中的sydney.auth功能可用。如果是这样,您应该将LoginController更改为:

function LoginController($scope, $state) {
  $scope.auth = sydney.auth;
}

您的代码正在做的是调用sydney.auth函数并将$scope.auth设置为其返回值,这不是我认为您的意图。