AngularJS design patterns: Should I use factories to create constructor functions?

angularjs, design-patterns, javascript

Solution

Yes!

Factories Syntax: module.factory( 'factoryName', function ); Result: When declaring factoryName as an injectable argument you will be provided the value that is returned by invoking the function reference passed to module.factory. Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances.

Source: https://groups.google.com/forum/#!msg/angular/56sdORWEoqg/HuZsOsMvKv4J

The above link is also used as the source to Bart's comment: AngularJS: Service vs provider vs factory

Problem

This is something I've been mulling over while creating an AngularJS app. When I first learned about AngularJS factories, I thought one clever usage of them would be to create and return a constructor function rather than a plain object, i.e. something like: ``` app.factory("Foo", function() { function Foo(bar, baz) { this.bar = bar; this.baz = baz; ... } Foo.prototype = { constructor: Foo, method1: function() { ... }, method2: function() { ... }, ..., methodn: function() { ... }, }; return Foo; }); ``` Then, you could inject the function into your controllers and call it with `new`. I found this aesthetically pleasing and OOP-y, but now I'm starting to think that it's actually an anti-pattern. The problem is that it works fine for when you're working within AngularJS-aware contexts, but once you want to, for instance, call the constructor from the console, use it in a Web Worker, or reuse the code in a non-AngularJS app, you start having to work around AngularJS rather than with it. I began to wonder if this approach was misguided insofar as functions in javascript already seem to be "singletons" and don't seem to need any help being instantiated. Am I misusing AngularJS factories? Would I be better served with constructor functions exposed to the global scope? More generally, are there specific factors which promote the usage of AngularJS factories/services/providers over global objects or vice versa?

Original source

Related problems