
In AngularJS, a Factory is a type of Service that returns an object, function, or value to other parts of your application. Factories are useful for organizing and sharing code across multiple components or controllers in your application.
Here’s a comparison table between Factories and Services:
Factories | Services | |
---|---|---|
Returns | An object, function or value | A new instance of the constructor function |
Singleton | No, new instance every time it is injected | Yes, only one instance per injector |
Usage | Creating singletons or returning objects, functions or values | Creating objects, functions or values that need to be instantiated multiple times |
Definition | Defined using the factory method of the module object | Defined using the service method of the module object |
Here’s an example of how to create a Factory in AngularJS:
angular.module('myApp', [])
.factory('myFactory', function() {
var factory = {};
factory.sayHello = function() {
return "Hello World!";
};
return factory;
});
In this example, we’re creating a factory called myFactory
that returns an object with a method sayHello
that returns the string “Hello World!”.
We can then use this factory in other parts of our application like this:
angular.module('myApp')
.controller('myController', function($scope, myFactory) {
$scope.message = myFactory.sayHello();
});
In this example, we’re injecting the myFactory
factory into a controller called myController
and using the sayHello
method to set the $scope.message
variable to “Hello World!”.
Overall, Factories are a great way to create reusable code in your AngularJS application.