After browsing several examples online, I have come across a common pattern in AngularJS code. The basic structure involves creating a new module using the angular.module()
method and then retrieving it in other files within the same module.
var app = angular.module("ExampleApp", []); // setter, creates a new module
app.controller(...
In subsequent files under the same Angular module, developers often retrieve the existing module like so:
var app = angular.module("ExampleApp"); // getter, retrieves the existing module
app.service(...
This practice introduces a global "app" variable that can be accessed across different files. However, there seem to be mixed opinions on whether it is preferable to skip the getter altogether and directly invoke app.service(...
.
While discarding the "getter" could raise concerns about best practices, some questions linger about the necessity of declaring the global variable at all. One suggestion is to encapsulate each file in an Immediately Invoked Function Expression (IIFE) to limit variable scope or eliminate the var app
declaration and chain methods like .controller
, .service
, etc. directly onto angular.module()
.
I welcome any expert advice on this matter. Thank you in advance for your insights.