AngularJS protips

Chained modules

Using var mod = angular.module('MyModule', []) to declare a module? Don’t.

As this plunkr demonstrates, mod will be accessible on the global scope (i.e. window.mod).

Same goes for var ctrl = mod.controller('MyCtrl').

As you’ve no-doubt heard, this is a bad idea as anything on window can be unwittingly overwritten. As a case in point, try uncommenting lines 6, then 35 in the aforementioned plunkr and opening up your browser’s console. window.angular no-more.

Unfortunately, Angular’s own documentation give examples in this way, for example the module docs (correct as of 78165c224d).

Using a “chained” module definition alleviates this problem, such as:

angular.module('MyModule', [])
  .controller('MyCtrl', function() {});

If your modules are starting to get large, use the “module retrieval” syntax (omit the dependency array argument) to get a reference to a previously declared module and continue the module definition in another file, e.g.:

angular.module('MyModule', []);

  .controller('MyCtrl', function() {});

Note: be careful not to pass the dependency array a second time as it will overwrite the previous module declaration!