Difference between factory and services in angular
Posted By : Archna Dhingra | 30-Jun-2015
Services
Service provider function creates a service object by using 'new' keyword and you can add properties to it using the new keyword and return it.
A service creates a global instance of the object, which is then injected in to the function. This instance is then instantiated with the 'new' keyword, properties are added to the same and then the service returns this object. When you pass the service into your controller, the properties on the object are now available in the controller through the injected service.
angularJS.service
module.service('dataService', function() {
this.methodName1 = function() {
//..return what you want to
}
this.methodName2 = function() {
//..return what you want to
}
});
Factory
Factory allows us to add some logic before creating the object we require. It differs from Service in a way where it allows us to pass the function which factory then invokes and returms the result.
A factory returns the functions return value, i.e. you just create an object, add properties to it, then return that same object. When you pass this service into your controller, those properties on the object will now be available in that controller through your factory.
angularJS.factory
module.factory('dataFactory', function() {
var factory = {};
factory.methodName = function() {
// your code
}
factory.methodName = function() {
// your code
}
return factory;
});
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Archna Dhingra
Archna is a bright Groovy and Grails developer and has worked on development of various SaaS applications using Grails framework.