我正在尝试使this快速入门指南中的代码“角度化”,以了解如何使用Google日历api。
我有以下代码。现在,我只是想创建一个页面,如果用户需要登录google,则显示true
,如果已经登录,则显示false
。
<html ng-app="calApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
var app = angular.module("calApp",[]);
app.controller('calController',function calController($scope){
gapi.auth.authorize({
'client_id': 'asdfghjkl123456',
'scope': 'https://www.googleapis.com/auth/calendar.readonly',
'immediate': true
}, function(authResult){
if (authResult && !authResult.error) {
$scope.needslogin = false;
}else{
$scope.needslogin = true;
}
});
});
</script>
</head>
<body ng-controller="calController">
{{needslogin}}
</body>
</html>
问题是gapi.auth.authorize部分给我一个错误,因为它尝试在
client.js
加载之前运行。解决此问题的预期方法是使用回调函数。所以我尝试
<script src="https://apis.google.com/js/client.js?onload=defineController"></script>
<script type="text/javascript">
var app = angular.module("calApp",[]);
function defineController(){
app.controller('calController',function calController($scope){
gapi.auth.authorize({
'client_id': 'asdfghjkl123456',
'scope': 'https://www.googleapis.com/auth/calendar.readonly',
'immediate': true
}, function(authResult){
if (authResult && !authResult.error) {
$scope.needslogin = false;
}else{
$scope.needslogin = true;
}
});
});
}
</script>
但是现在我得到一个错误,因为在
<body ng-controller="calController">
尝试运行时未定义控制器。有关如何正确执行此操作的任何提示将不胜感激。
最佳答案
引导后无法定义控制器
尝试
<script src="https://apis.google.com/js/client.js?onload=gapiBootCallback"></script>
<script type="text/javascript">
var gapiBootStrapper = {}; // an object that you can attach a callback function to in the controller
var app = angular.module("calApp", []).constant('gapiBootStrapper', gapiBootStrapper); // Passing it into Angular as a constant is not necessary but stop us using global from within a controller
function gapiBootCallback() {
gapi.auth.authorize({
'client_id': 'asdfghjkl123456',
'scope': 'https://www.googleapis.com/auth/calendar.readonly',
'immediate': true
}, function (authResult) {
if (authResult && !authResult.error) {
gapiBootStrapper.callback(false);
} else {
gapiBootStrapper.callback(true);
}
});
}
app.controller('calController', function calController($scope, $timeout, gapiBootStrapper) {
gapiBootStrapper.callback = function (needslogin) {
$timeout(function () { // Use $timeout so we don't need to call $scope.$apply
$scope.needslogin = needslogin;
});
};
});
</script>