Coding style in AngularJS
angularjs, coding-style
Solution
- 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){ ... }]);
Problem
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?