In AngularJS, services are essential for sharing data and logic across the application. One way to create a service is by using a Factory Provider. A factory in AngularJS is a design pattern that allows you to create reusable, shareable logic that can be injected into controllers, directives, and other components.
1. What is a Factory in AngularJS?
A factory in AngularJS is a type of provider that returns an object or function. It is one of the ways to create services and is recommended for encapsulating reusable logic.
Key Features of a Factory Provider
✔ Creates and returns objects (or functions).
✔ Used for data sharing and business logic encapsulation.
✔ Supports lazy initialization (created only when first used).
✔ Easily testable and reusable.
2. Syntax of a Factory
app.factory('FactoryName', function() {
return {
method1: function() {
return "Hello from Factory!";
}
};
});
- The factory function returns an object that contains properties/methods.
- This object is available wherever the factory is injected.
3. Creating a Factory Provider (Step-by-Step)
Step 1: Define an AngularJS Module
First, define the AngularJS module where the factory will be used.
var app = angular.module('myApp', []);
Step 2: Create a Factory
Define a factory that returns an object with methods.
app.factory('MathService', function() {
return {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
}
};
});
- Here,
MathService
provides addition and subtraction methods.
Step 3: Inject and Use the Factory in a Controller
Now, inject the factory into a controller and use its methods.
app.controller('MainController', function($scope, MathService) {
$scope.num1 = 10;
$scope.num2 = 5;
$scope.sum = MathService.add($scope.num1, $scope.num2);
$scope.difference = MathService.subtract($scope.num1, $scope.num2);
});
$scope.sum
stores the result of addition.$scope.difference
stores the result of subtraction.
Step 4: Bind Data to the View (HTML)
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS Factory Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainController">
<p>Number 1: {{ num1 }}</p>
<p>Number 2: {{ num2 }}</p>
<p>Sum: {{ sum }}</p>
<p>Difference: {{ difference }}</p>
</body>
</html>
- This binds the factory’s methods to an AngularJS controller and displays results in the UI.
4. Factory vs Service vs Provider
Feature | Factory (.factory ) | Service (.service ) | Provider (.provider ) |
---|---|---|---|
Returns | An object | An instance (via this ) | A customizable provider |
How to use? | Return an object with methods | Use this to define methods | Use $get() to return an object |
Best for? | Encapsulating logic | Simple objects/classes | Advanced use cases (configurable) |
Example Comparison
Factory
app.factory('ExampleFactory', function() {
return {
sayHello: function() {
return "Hello from Factory!";
}
};
});
Service
app.service('ExampleService', function() {
this.sayHello = function() {
return "Hello from Service!";
};
});
Provider
app.provider('ExampleProvider', function() {
this.$get = function() {
return {
sayHello: function() {
return "Hello from Provider!";
}
};
};
});
Key Takeaway: Use .factory
for most cases, .service
for object-based services, and .provider
when you need configurable services.
5. Advanced Use Case: Factory with API Calls
Factories are also useful for handling API requests with $http
.
Example: Fetching Data from an API
app.factory('UserService', function($http) {
var apiUrl = "https://jsonplaceholder.typicode.com/users";
return {
getUsers: function() {
return $http.get(apiUrl).then(function(response) {
return response.data;
});
}
};
});
Using the Factory in a Controller
app.controller('UserController', function($scope, UserService) {
UserService.getUsers().then(function(users) {
$scope.users = users;
});
});
Displaying API Data in HTML
<div ng-controller="UserController">
<ul>
<li ng-repeat="user in users">{{ user.name }}</li>
</ul>
</div>
What happens?
- The factory calls the API and returns data.
- The controller fetches and binds it to
$scope.users
. - The view displays user names in a list.
6. When to Use a Factory?
✔ Reusable business logic – Encapsulate logic like authentication, calculations, or API calls.
✔ Data sharing – Store and manage application-wide data.
✔ API integration – Fetch data from a server and return responses.
✔ State management – Maintain the application’s shared state.