It took me one day to make it works so I think my experience may be useful from someone. And maybe some others will find improvement.
So I start angularJS two days ago. And I want it works with Google Cloud Endpoints to create a backend interface. Here comes the trouble for me.
The javascript client for gapi comes with asynchronous loading, so angular initialization will crash having gapi undefined.
So you need to bootstrap angular when gapi is initialized:
- remove ng-app="myApp"
- Add
<script src="https://apis.google.com/js/client.js?onload=googleOnLoadCallback"></script>
Add the callback:
function googleOnLoadCallback(){
var apisToLoad = 1; // must match number of calls to gapi.client.load()
var gCallback = function() {
if (--apisToLoad == 0) {
//Manual bootstraping of the application
var $injector = angular.bootstrap(document, ['myApp']);
console.log('Angular bootstrap complete ' + gapi);
};
};
gapi.client.load('helloWorld', 'v1', gCallback, '//' + window.location.host + '/_ah/api');
}
Feel good but how about a call ?
So here is the controller:
angular.module('myApp.controllers', []).
.controller('MyCtrl', ['$scope' ,'helloWorldService',
function($scope,greetingsService) {
helloWorldService.loadData($scope);
}]);
And here is the service:
angular.module('myApp.services', [])
service('helloWorldService', [function() {
this.loadData = function($scope) {
//Async call to google service
gapi.client.helloWorld.greetings.listGreeting().execute(
function(resp) {
if (!resp.code) {
console.debug(resp);
$scope.greetings = resp.items;
// Because it's a callback,
// we need to notify angular of the data refresh...
$scope.$apply();
}
});
};
}]);
And magically your page updates thanks to angular.
Feel free to mark anywhere I go wrong.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…