Service and Factory both just a simple function. Service acts as a constructor function but Factory is really just a function that gets called, which is why we have to return an object explicitly. We can create & return anything that's why Factory is much more powerful and flexible.
reference: https://toddmotto.com/factory-versus-service
app.service('MyService', function () {
this.sayHello = function () {
console.log('hello');
};
});
app.controller('AppController', function (MyService) {
MyService.sayHello(); // logs 'hello'
});
function InboxFactory($http) {
function getEmails() {
return $http.get('/emails');
}
return {
getEmails: getEmails
};
}
angular
.module('app')
.factory('InboxFactory', InboxFactory);
app.service('myService', function() {
// service is just a constructor function
// that will be called with 'new'
this.sayHello = function(name) {
return "Hi " + name + "!";
};
});
app.factory('myFactory', function() {
// factory returns an object
// you can run some code before
return {
sayHello : function(name) {
return "Hi " + name + "!";
}
}
});