onmyway onmyway - 1 year ago 68
AngularJS Question

Correct way to set up an AngularJS app i.t.o the Global Namespace?

I have inherited an AngularJS app that another developer has developed. And I am now to further develop and support this app.

One thing I immediately noticed, was the way in which he declared his app and controllers, not using the IIFE (immediately invoked function expression) syntax, or assigning the app and modules to variables.

He declared everything in the following format:

The app module:

'use strict';

.module('app', [


Example controller:

'use strict';


['$scope', function($scope) {


Instead of using something like this (IIFE):

(function () {

'use strict';



Or this:

var app = angular.module('app', [



Will the method used by the previous developer potentially dirty the global namespace with clashing variables etc.?

As I understand it, and IIFE is useful and recommended for the following reasons:

Why?: An IIFE removes variables from the global scope. This helps prevent variables and function declarations from living longer than expected in the global scope, which also helps avoid variable collisions.

Why?: When your code is minified and bundled into a single file for deployment to a production server, you could have collisions of variables and many global variables. An IIFE protects you against both of these by providing variable scope for each file.

Answer Source

In the code above nothing leaks to global namespace (except angular global which leaks in any case). There are no named functions or temporary variables like app.

Angular offers angular.module method chaining and inline array annotation exactly to permit comfortable development with no IIFEs or bundling system.

If there is a need to define a variable outside of factory function (this is the case for constant service), an IIFE should be used:

angular.module(...).constant('constant', (() => {
  var constant = ...;
  return constant;

For highly modular application (one Angular module per file) it is possible to get rid of angular.module('moduleName') module getters and rely on Angular modules for dependency handling, this allows to not keep module order when loading or bundling files. This also fits the picture.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download