richard
richard

Reputation: 12498

Why is an angularjs factory called a 'factory'?

What, if anything, does it have to do with the factory pattern?

Or if nothing, then why is it called a factory? It seems more like a singleton to me.

Upvotes: 2

Views: 224

Answers (1)

Michal Charemza
Michal Charemza

Reputation: 27012

My guess is that a factory can be used to create factory functions

app.factory('MyFactory', function() {
  // The returned function is available by injecting MyFactory
  // into other components
  return function() {
    return 'Something created by the factory';
  };
});

This can be used, for example, in a controller

app.controller('MyController', function(MyFactory) {
  var myObj = MyFactory();
  // myObj is 'Something created by the factory'
});

(You can do something like this using service as well. I think you just have to live with the fact there is almost complete overlap between what you can do with factory and service)

Upvotes: 1

Related Questions