AngularJS Services
AngularJS services are singleton objects that provide reusable functionality, created once per application and shared via dependency injection.
What Is a Service?
A service in AngularJS is an object that carries out a specific, reusable task — such as formatting data, storing shared state, or talking to a server. AngularJS creates a service only once per application: it is a singleton, and the same instance is handed to every controller or other service that requests it.
Services are made available through dependency injection: you simply list the service name as a parameter in a controller or another service's constructor function, and AngularJS supplies the matching instance.
Defining a Custom Service
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<script>
var app = angular.module("myApp", []);
app.service("hexafy", function() {
this.myFunc = function(num) {
return num.toString(16);
};
});
</script>
</body>
</html>Using a Service in a Controller
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<script>
var app = angular.module("myApp", []);
app.service("hexafy", function() {
this.myFunc = function(num) {
return num.toString(16);
};
});
app.controller("myCtrl", function($scope, hexafy) {
$scope.hex = hexafy.myFunc(255);
});
</script>
</body>
</html>Built-in Services
AngularJS ships with a number of built-in services, always prefixed with $, such as $http for server communication, $location for the current URL, and $timeout for deferred execution. These are injected exactly the same way as custom services.
Dependency Injection
Dependency injection means a component declares what it needs as parameters, and AngularJS resolves and provides those dependencies automatically, rather than the component creating or looking them up itself. This keeps controllers and services loosely coupled and easy to test.
- Because services are singletons, data stored on a custom service persists and stays shared across every controller that injects it.
- AngularJS matches injected dependencies by parameter name, so the argument name in your function must match the registered service name.
- Custom services can themselves depend on other services, including $http, simply by listing them as parameters.
Exercise: AngularJS Services
What is a defining characteristic of an AngularJS service instance?