1

I wonder if it is worth writing angular stuff this way:

(function(angular, module) {

  'use strict';

  module.controller('MyCtrl', function($scope) {
    // possibly use helperFunction here
  });

  function helperFunction() {
    ...
  }

})(angular, angular.module('myModule'));

or this way (using App object and putting app stuff into it:

App = App || {};

App.myModule = App.myModule || angular.module('myModule', []);

App.myModule.controller('MyCtrl', function($scope) {

  'use strict'

  // possibly use helperFunction here

  function helperFunction() {
    ...
  }

});

than using regular way like this

angular.module('myModule').controller('MyCtrl', function($scope) {

  'use strict'

  // possibly use helperFunction here

  function helperFunction() {
    ...
  }

});

Those are three possible ways (not counting requirejs) of structuring app code that come to my mind. I'm using "regular" one (the last) as seen in most places, but I wonder if there are any benefits of using those two former approaches. Maybe there are special cases when those are useful, I'm not aware of.

2 Answers 2

1

The first approach has the benefit of not polluting the global namespace thus reducing the risk of name clash. This is especially important if you extend an existing project or if your module will be used in multiple context (for example a public library).

I personally prefer the third style over the second for no particular reason. One could argue that optimizers are better at optimizing non global code.

Sign up to request clarification or add additional context in comments.

Comments

0

The answer is pretty simple. Its the idea behind "Dependency Injection" (see angular docs for more info). By using Angular's built in modules, you can declare dependencies on those modules later on when you use them. This is critically important to being able to do easy unit testing. Not being in the global namespace is part of the issue, but the larger issue is that (in each subsequent module) you can declare which other modules your current module relies on.

Here's a decent article that explains more on this topic: http://joelhooks.com/blog/2013/08/18/configuring-dependency-injection-in-angularjs/

1 Comment

But I guess none of those approaches kills dependency injection idea. All Angular DI stuff is still working fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.