After reviewing the recipe on how to connect an AngularJS frontend with a Google Cloud Endpoints backend, I still have questions about the AngularJS and Cloud Endpoints initialization process. The relevant section in question is as follows:
Appendix: Tips on AngularJS + Cloud Endpoints Initialization Tip #1: Pay attention to the order of initialization
In the guestbook app, three JS libraries are loaded in a specific sequence:
- AngularJS
- The guestbook app
- Google API Client, which includes Endpoints functionalities
To adhere to this order, the index.html file includes the following
<script>
tags within the<head>
tag to load each JS library:<script src="js/angular.min.js"></script> <script src="js/guestbook.js"></script> <script src="https://apis.google.com/js/client.js?onload=init"></script>
Once loaded, the third library (Google API Client) calls the initialization function specified by its ‘onload’ parameter, which is expected to be the init() function. Tip #2: Dive into the AngularJS environment as soon as possible
During initialization, two functions are used:
init() function window.init() function
The init() function is defined in guestbook.js as follows:
function init() { window.init(); }
As seen in the code snippet above, this function simply calls the window.init() function (which is the init() function defined globally in the window object) and nothing else. The window.init() function is defined within the AngularJS controller as shown below:
$window.init= function() { $scope.$apply($scope.load_guestbook_lib); };
In AngularJS, the global window object is accessed using the “$window” notation as a wrapper for it. It is a recommended practice in AngularJS to avoid direct access to the window object for better testability.
The reason for delaying the execution of the initialization in the first init() method is to move as much code as possible into the AngularJS realm, including controllers, services, and directives. This allows you to leverage the full potential of AngularJS and efficiently conduct unit tests, integration tests, and more.
It appears that a global function called init()
is defined within an external JavaScript file. This init()
function simply triggers window.init()
(expected to be triggered by the Google client library after loading). However, isn't window.init() essentially the globally defined init()
function? Would this not result in a loop until window.init()
(and therefore init()
) is redefined?