Difference between factory and services in angular

Posted By : Archna Dhingra | 30-Jun-2015

Difference between factory and services in angular

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;
});
 
Thanks
Archna Dhingra

About Author

Author Image
Archna Dhingra

Archna is a bright Groovy and Grails developer and has worked on development of various SaaS applications using Grails framework.

Request for Proposal

Name is required

Comment is required

Sending message..