John Papa's famous Angular 1 Style Guide says to use IIFEs, to avoid the likes of var myApp = angular.module('myApp',[]);
and polluting the global namespace.
The example given is:
(function() {
'use strict';
angular
.module('app')
.factory('logger', logger);
function logger() { }
})();
(function() {
'use strict';
angular
.module('app')
.factory('storage', storage);
function storage() { }
})();
How does this work? Do I not need to declare the module at least once? E.g with angular.module('app',[]);
(wrapped in an IIFE? (instead of var app = angular.module('app',[]);
to avoid a global variable))?
However, the two usages of angular.module('app')
in the example , do not declare, but will then evaluate angular.module('app')
twice, which surely cannot be A Good Thing (in fact, I read a highly upvoted S.O. question earlier which said that this is A Bad Thing, and that there should be a single reference - but that would be a global, which is also A Bad Thing).
Which is it to be? Or can I declare my angular.module('app')
, plus a few controllers, serves, factories, directives, in separate files, in separate IIFEs? If so, how?
Do I not need to declare the module at least once?
Yes, the module needs to be created with dependencies first:
angular.module('app',['ngRoute']);
This must be done before any subsequent scripts add to it. It need not be enclosed in an IIFE because it doesn't declare any global variables.
To avoid pollution of the global namespace, the following needs to be enclosed in an IIFE:
(function() {
'use strict';
angular
.module('app')
.factory('logger', logger);
function logger() { }
})();
'use strict';
angular.module('app')
.service('storage', function storage() {
var value;
this.get = function() { return value; };
this.set = function(val) {
value = val;
};
})
This does not need an IIFE because it does not declare any global variables or functions.
Both examples avoid polluting the global namespace.
For more information, see