Issue
It says that Angular JS Services are singleton objects which are instantiated only once in app. In terms of instantiation, how different is it from Angular JS factories or controllers?
Answers with a fiddle will be helpful.
Solution
There is no factory
component in AngularJS. A factory is a function, passed to module.factory()
, whose responsibility is precisely to create the service instance. This factory is called only once by Angular, to create the unique instance of the service. This unique instance, returned by the factory function, is then injected everywhere the service is needed.
So, in short, when you do
app.factory('foo', function() {
var service = {};
...
return service;
});
You're not defining a factory. You're passing a factory function to app.factory()
, and this factory creates and returns the service instance. 'foo'
is the name of the service.
A controller is not a singleton at all. Every time ng-controller="FooCtrl"
is used, or FooCtrl is used in some route or directive, a new instance of FooCtrl
is created.
Answered By - JB Nizet
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.