AngularJS Services

AngularJS Services

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.


What is a Service?

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).


Creating Custom Services

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.

Custom Service Example:

<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>


SEO and Best Practices

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.


Exercise 1 of 1

?

How can you tell if an AngularJS variable is a built-in service?