Friday, February 12, 2016

How to use factory or service in AngularJS

As a beginner in AngularJS it is very important to understand Service/Factory. AngularJS provides many services itself and we can use those services whenever we required, just by injecting in controller/module.

when we need to share some functions or some data we can create our own service/factory and have all the methods/data in that. To use these service's method or data we just need to inject that service and use.

For example if we want to share one data object in 2 different controller, say controller1 and controller2. We Create one service dataService

 var app = angular.module("app",[]);
 app.factory('dataService',['$http', function($http){
  var dataService = {};
  dataService.method1 = function(){
    console.log("method1 executing");
  };
  dataService.method2 = function(){
    console.log("method2 executing");
  };
  return dataService;
 }]);
 

Now we can use this service in any controller by injecting

app.controller('controller1',['dataService','$scope' function(dataService,$scope){
 dataService.method1();  // it will print 'method1 executing'
 dataService.method2();  // it will print 'method2 executing'
}]);
app.controller('controller2',['dataService','$scope' function(dataService,$scope){
 dataService.method1();  // it will print 'method1 executing'
 dataService.method2();  // it will print 'method2 executing'
}]);

In same way we can create service also instead of factory, the only difference between factory and service is that, service is constructor function while in factory we need to return the object. For same objective we can create service as follows:

 app.service('dataService',['$http', function($http){
  this.method1 = function(){
    console.log("method1 executing");
  };
  this.method2 = function(){
    console.log("method2 executing");
  };
 }]);