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;
});
Services are defined by their constructor function, and operate on
this
Factories return an object, and that object can be anything
Best practice is generally to use a Service
var application = angular.module('app',[]);
.controller("MainController",
function($scope, MathFactory, CalcService){
console.log(MathFactory.square(2));
console.log(CalcService.square(2));
}
}
application.service('CalcService', function(){
this.square = function(a) {
return a * a;
}
});
application.factory('MathFactory', function() {
var factory = {};
factory.square = function(a) {
return a * a;
}
return factory;
});