We are using service,factory and provider in the modules of angularjs.my Question is what is the difference among each other and at what condition they should be used in angularjs.please solve my doubt.
Asked
Active
Viewed 150 times
0
-
Someone already asked the same question here, look at this: http://stackoverflow.com/a/15666049/3067900 ;) – Sirikon Feb 23 '15 at 10:30
-
http://stackoverflow.com/questions/15666048/service-vs-provider-vs-factory U can find the clear explanation here... – Vicky Feb 23 '15 at 10:33
1 Answers
0
A service is a class
. You should provide a service with a constructor
function. Angular will only instantiate (new up) one instance of this class
. It is a singleton.
angular.module('app', [])
.service('someService', SomeService);
SomeService.$inejct = ['dependency'];
function SomeService(dependency) {
this.foo = 'foo'
// . . .
}
SomeService.prototype.bar = function() {
return 'bar';
}
A factory expects the function passed to it to follow the JavaScript factory pattern
. This is a function that is not newed up, and returns a unique object. Angular will only call this factory once -- so it too is a singleton.
angular.module('app', [])
.factory('someFactory', ['dependency', someFactory]);
function someFactory(dependency) {
return {
foo: 'foo',
bar: function() {
return 'bar';
}
}
}
A provider is a class
that allows you to configure a service during the config time
angular.module('myApp', [])
.provider('someService', SomeServiceProvider);
function SomeServiceProvider() {
this.foo = 'foo'
this.bar = 'bar';
}
SomeServiceProvider.prototype.setFooBar = function(foo, bar) {
this.foo = foo;
this.bar = bar;
}
SomeServiceProvider.prototype.$get = function() {
return new SomeService(this.foo, this.bar);
}
function SomeService(foo, bar) {
this.foo = foo;
this._bar = bar;
// . . .
}
SomeService.prototype.bar = function() {
return this._bar;
}
So now in the config portion of a module you can do someServiceProvider.setFooBar('baz', 'buz')

Martin
- 15,820
- 4
- 47
- 56