[AngularJS] Best Practise - Factory & Services
Services:
Services are instantiated and should be class-like also and reference the this
keyword, keep function style consistent with everything else.
Good:
function SomeService () { this.someMethod = function () { }; } angular .module('app') .service('SomeService', SomeService);
Factory:
Factories give us a singleton module for creating service methods (such as communicating with a server over REST endpoints). Creating and returning a bound Object keeps controller bindings up to date and avoids pitfalls of binding primitive values.
Important: A "factory" is in fact a pattern/implementation, and shouldn't be part of the provider's name. All factories and services should be called "services".
Bad:
function AnotherService () { var someValue = ''; var someMethod = function () { }; return { someValue: someValue, someMethod: someMethod }; } angular .module('app') .factory('AnotherService', AnotherService);
Good:
We create an Object with the same name inside the function. This can aid documentation as well for comment-generated docs.
function AnotherService () { var AnotherService = {}; AnotherService.someValue = ''; AnotherService.someMethod = function () { }; return AnotherService; } angular .module('app') .factory('AnotherService', AnotherService);
Any bindings to primitives are kept up to date, and it makes internal module namespacing a little easier, we can easily see any private methods and variables.