Service
Services are javascript functions and are responsible to do a specific tasks only. This makes them an individual entity which is maintainable and testable. Controllers, filters can call them as on requirement basis. Services are normally injected using dependency injection mechanism of AngularJS.
Type of services
Factory
Factories are the most popular way to create and configure a service. There’s really not much more than what the said. You just create an object, add properties to it, then return that same object. Then when you pass the factory into your controller, those properties on the object will now be available in that controller through your factory.
Service
A service is a constructor function whereas a factory is not. Somewhere deep inside of this Angular world, there’s this code that calls Object.create() with the service constructor function, when it gets instantiated.
var app = angular.module('app', [])
.factory('factoryService', function() {
return {
sayHello: function(text) {
return "Factory says \"Hello " + text + "\"";
},
sayGoodbye: function(text) {
return "Factory says \"Goodbye " + text + "\"";
}
}
})
.service('serviceService', function() {
this.sayHello = function(text) {
return "Service says \"Hello " + text + "\"";
};
this.sayGoodbye = function(text) {
return "Service says \"Goodbye " + text + "\"";
};
})
.controller('HelloCtrl', ['$scope', 'factoryService', function($scope, factoryService) {
$scope.fromService = factoryService.sayHello("World");
$scope.fromFactory = factoryService.sayHello("World");
}])
.controller('GoodbyeCtrl', ['$scope', 'serviceService', function($scope, serviceService) {
$scope.fromService = serviceService.sayGoodbye("World");
$scope.fromFactory = serviceService.sayGoodbye("World");
}]);