Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coding style in AngularJS

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?

like image 491
Tiberiu F. Avatar asked Nov 28 '13 14:11

Tiberiu F.


People also ask

How to name services in Angular?

Service nameslink Do suffix a service class name with Service . For example, something that gets data or heroes should be called a DataService or a HeroService .

What is the name of the decorator conventionally added to all angular services?

Every Angular app has a root module, conventionally named AppModule, which provides the bootstrap mechanism that launches the application. An app typically contains many functional modules. Modules are decorated with @NgModule.

What is the naming convention of built in directives in angular 2?

Naming Convention: *[name of directive] — Upper camel case is used for the directive class, while lower camel case is used for the directive's name. What sets them apart from other directives in Angular 2: Reshape DOM structure by adding or removing existing DOM elements and do not have templates.


2 Answers

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.
like image 24
Golo Roden Avatar answered Oct 10 '22 16:10

Golo Roden


  • 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){ ... }]);
like image 109
Stewie Avatar answered Oct 10 '22 16:10

Stewie