5

While this thread sums up the following three code styles:

1)

angular.module('mainCtrl', []);
function MainCrl($scope, $rootScope) {}

2)

angular.module('mainCtrl',[])
.controller('MainCtrl', function($scope, $rootScope)) { ... });

3)

angular.module('mainCtrl',[])
.controller('MainCtrl', ['$scope', '$rootScope', function(scope, rootScope)) { ... }]);

there's a fourth way i've seen in this video that is very appealing for me

4)

var controllers = {}
controllers.mainCtrl = function($scope, $rootScope){ };
app.controller(controllers)

I am leaning towards continuing with 4), will it break if minified or are there any other drawbacks? Should i just go with 3) since it seems to be the standard way of doing it?

1
  • 2
    Yes, number 4 will break if minified. Commented Nov 28, 2013 at 14:50

2 Answers 2

5
  • Option 1 pollutes global namespace and hinders minification and does not respect modules.
  • Option 2 does not let you rename your injectables in controller signature.
  • Option 4 pollutes global namespace, but it is minification-safe if you do it properly1.

  • Option 3 lets you rename your injectables2, does respect modules, does not pollute global namespace, and does not require any extra work when minifying.

So my winner is option #3.


1 Option 4 - minification-friendly version:

var controllers = {};
controllers.mainCtrl = ['$scope', '$rootScope', function($scope, $rootScope){ ... }];
app.controller(controllers);

2 Renaming injectables:

app.controller('MyCtrl', ['$scope', 'UserService', function($scope, User){ ... }]);
Sign up to request clarification or add additional context in comments.

Comments

5

My recommendation: Go with option 3, for three reasons:

  1. It is (IMHO) the most widely adopted one.
  2. You have no problems with minification (and this is the only option where this is true).
  3. It works best with modules.

Comments

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.