A service is a "singleton". A single object shared anywhere it is injected.
Even though they are called Factories, these are still just singletons.
Service
Instance
Controllers
Factory
Instance
Controllers
mainApp.service('CalcService', function(){
this.square = function(a) {
return a * a;
}
});
mainApp.factory('MathService', function() {
var factory = {};
factory.square = function(a) {
return a * a;
}
return factory;
});
Frankly, it's unclear to the community why there are two.
Most people have agreed that the best practice is to use factories, because we get slightly more flexibility.
var application = angular.module('app',[]);
.controller("MainController",
function($scope, MathService, CalcService){
console.log(MathService.square(2));
console.log(CalcService.square(2));
}
}
application.service('CalcService', function(){
this.square = function(a) {
return a * a;
}
});
application.factory('MathService', function() {
var factory = {};
factory.square = function(a) {
return a * a;
}
return factory;
});