![]()
1. What is a Singleton Service in AngularJS?
A Singleton Service in AngularJS is a service that maintains a single instance across the application. This means that every time the service is injected, the same instance is used, allowing data to be shared across controllers and components.
Why Use Singleton Services?
Efficient Memory Usage – Only one instance is created.
Shared State – Allows different parts of the app to access the same data.
Encapsulation – Keeps logic separate from controllers.
Better Code Organization – Promotes modular architecture.
2. Ways to Create a Singleton Service in AngularJS
AngularJS provides different ways to create singleton services:
- Factory (
.factory()) - Service (
.service()) - Provider (
.provider())
3. Creating a Singleton Service Using .service()
The .service() method is commonly used for creating singleton services. It works by instantiating the service using the new keyword.
Example: A Singleton Authentication Service
var app = angular.module("myApp", []);
app.service("AuthService", function() {
this.isAuthenticated = false;
this.login = function() {
this.isAuthenticated = true;
};
this.logout = function() {
this.isAuthenticated = false;
};
this.getAuthStatus = function() {
return this.isAuthenticated;
};
});
How to Use the Service in a Controller
app.controller("LoginController", function($scope, AuthService) {
$scope.login = function() {
AuthService.login();
};
$scope.logout = function() {
AuthService.logout();
};
$scope.checkStatus = function() {
return AuthService.getAuthStatus();
};
});
AuthService maintains the authentication state across the app.
4. Creating a Singleton Service Using .factory()
A factory function returns an object, making it another way to create a singleton service.
Example: A Data Sharing Factory
app.factory("DataService", function() {
var data = {
message: "Hello, World!"
};
return {
getMessage: function() {
return data.message;
},
setMessage: function(newMessage) {
data.message = newMessage;
}
};
});
How to Use the Factory in a Controller
app.controller("MessageController", function($scope, DataService) {
$scope.message = DataService.getMessage();
$scope.updateMessage = function(newMessage) {
DataService.setMessage(newMessage);
};
});
DataService ensures all controllers access the same shared message.
5. Creating a Singleton Service Using .provider()
The .provider() method allows customization during the configuration phase.
Example: A Configurable API Service
app.provider("ApiService", function() {
var apiUrl = "";
this.setApiUrl = function(url) {
apiUrl = url;
};
this.$get = function() {
return {
getApiUrl: function() {
return apiUrl;
}
};
};
});
// Configuring the provider
app.config(function(ApiServiceProvider) {
ApiServiceProvider.setApiUrl("https://api.example.com");
});
How to Use the Provider in a Controller
app.controller("ApiController", function($scope, ApiService) {
$scope.apiUrl = ApiService.getApiUrl();
});
ApiService is configurable at the app level.
