In AngularJS, a Service is a reusable function or object available to your entire app.
They handle complex logic, data fetching, and sharing data between controllers.
Controllers are meant strictly for managing the View state.
If you need to calculate complex math or talk to a database, you write a Service.
AngularJS provides many built-in services, all prefixed with a $ symbol (like $http or $timeout).
You can easily define your own custom service using app.service().
Once defined, you simply "inject" it into any controller that needs it!
This promotes perfectly modular and reusable code architecture.
<div ng-app="myApp" ng-controller="myCtrl">
<p>Result from Service: {{ convertedValue }}</p>
</div>
<script>
var app = angular.module('myApp', []);
// Defining the custom service
app.service('MathService', function() {
this.doubleValue = function(x) { return x * 2; }
});
// Injecting the service into the controller
app.controller('myCtrl', function($scope, MathService) {
$scope.convertedValue = MathService.doubleValue(10);
});
</script>
Using services keeps your application lightweight and incredibly fast.
Fast, highly optimized code decreases load times, directly boosting your SEO score.
Always move heavy database interactions out of controllers and into services.
How can you tell if an AngularJS variable is a built-in service?