A factory is a simple function which allows you to add some logic before creating the object. In the end, it returns the created object.
Syntax.
app.factory('serviceName',function(){ return serviceObj;})
Creating Service Using The Factory Method.
JavaScript
<script>
//creating module
var app = angular.module('app', []);
//define a factory using factory() function
app.factory('MyFactory', function () {
var serviceObj = {};
serviceObj.function1 = function () {
//TO DO:
};
serviceObj.function2 = function () {
//TO DO:
};
return serviceObj;
});
</script>
When To Use Factory?
It is just a collection of functions, like a class. Hence, it can be instantiated in different controllers when you are using it with a constructor function.