From "AngularJS - From Nutshell To Awesome" by Henry Tao
Structure
DRY
Testability
Separating code into distinct sections, so that each section addresses a separate concern.
Makes it easier to:
From "The Art of AngularJS" by Matt Raible
From "AngularJS: Introduction and Sample Programs" by Amaury Valdes
From "Learn Simple AngularJS Thanks to Best Practices" by Daniel Mettler
From "Learn Simple AngularJS Thanks to Best Practices" by Daniel Mettler
/app /assets /scripts /tests
App/ Controllers/ Services/ Views/
App/ /core /pubs /parks /transport
This example defines the app module and its dependencies, defines a controller, and defines a factory all in the same file.
/* avoid */
angular
.module('app', ['ngRoute'])
.controller('SomeController', SomeController)
.factory('someFactory', someFactory);
function SomeController() { }
function someFactory() { }
It is best practice to separate each component into its own file.
/* recommended */
// app.module.js
angular
.module('app', ['ngRoute']);
/* recommended */
// someController.js
angular
.module('app')
.controller('SomeController', SomeController);
function SomeController() { }
/* recommended */
// someFactory.js
angular
.module('app')
.factory('someFactory', someFactory);
function someFactory() { }
You run the risk of your code being overwritten by any other JavaScript added to the page after yours.
Can be hard to keep track of where and when global variables are being used
Instead...
/* avoid */
// logger.js
angular
.module('app')
.factory('logger', logger);
// logger function is added as a global variable
function logger() { }
// storage.js
angular
.module('app')
.factory('storage', storage);
// storage function is added as a global variable
function storage() { }
/**
* recommended
*
* no globals are left behind
*/
// logger.js
(function() {
'use strict';
angular
.module('app')
.factory('logger', logger);
function logger() { }
})();
// storage.js
(function() {
'use strict';
angular
.module('app')
.factory('storage', storage);
function storage() { }
})();
Modules are containers of Angular components. Modules can be grouped into 3 categories:
(JS Fiddle Demo)
For Registering, Injecting and Defining Components
angular
.module('app.pubs', [])
.controller('Pubs',['core’,’dataservice',Pubs]);
function Pubs(core, dataservice) {
//controller goes here
}
function Pubs(core, dataservice) {
//controller goes here
}
Pubs.$inject = ['core’,’dataservice']);
angular
.module('app.pubs', [])
.controller('Pubs',Pubs]);
angular
.module('app.pubs', [])
.controller('Pubs',Pubs]);
Pubs.$inject = ['core’,’dataservice'];
function Pubs(core, dataservice) {
//controller goes here
}
angular
.module('app.pubs', [])
.controller('Pubs',Pubs]);
/* @ngInject */
function Pubs(dataservice) {
//controller goes here
}
Avoid:
Use: