Mastering Web Application

(Rick Simeone) #1
Chapter 1

Factories


The factory method is another way of registering recipes for objects creation. It
is more flexible as compared to the service method, since we can register any
arbitrary object-creating function. An example is shown in the following code


myMod.factory('notificationsService',function(notificationsArchive){

var MAX_LEN = 10;
var notifications = [];

return {
push:function (notification) {
var notificationToArchive;
var newLen = notifications.unshift(notification);

//push method can rely on the closure scope now!
if (newLen > MAX_LEN) {
notificationToArchive = this.notifications.pop();
notificationsArchive.archive(notificationToArchive);
}
},
// other methods of the NotificationsService
};

AngularJS will use a supplied factory function to register an object returned. It
can be any valid JavaScript object, including function objects!


The factory method is the most common way of getting objects into AngularJS
dependency injection system. It is very flexible and can contain sophisticated
creation logic. Since factories are regular functions, we can also take advantage
of a new lexical scope to simulate "private" variables. This is very useful as we can
hide implementation details of a given service. Indeed, in the preceding example
we can keep the notificationToArchive service, all the configuration parameters
(MAX_LEN) and internal state (notifications) as "private".


Constants


Our NotificationsService is getting better and better, it is decoupled from its
collaborators and hides its private state. Unfortunately, it still has a hard-coded
configuration MAX_LEN constant. AngularJS has a remedy for this, that is, constants
can be defined on a module level and injected as any other collaborating object.

Free download pdf