AngularJS Services


In AngularJS you can make your own service, or use one of the many built-in services.

What is a Service?

In AngularJS, a service is a function, or object, that is available for, and limited to, your AngularJS application. AngularJS has about 30 built-in services. One of them is the $location service.

The $location service has methods which return information about the location of the current web page:

Output :

Why use Services?

For many services, like the $location service, it seems like you could use objects that are already in the DOM, like the window.location object, and you could, but it would have some limitations, at least for your AngularJS application.

AngularJS constantly supervises your application, and for it to handle changes and events properly, AngularJS prefers that you use the $location service instead of the window.location object.


The $http Service

The $http service is one of the most commonly used services in AngularJS applications. The service makes a request to the server, and lets your application handle the response.

Output :

The $timeout Service

The $timeout service is AngularJS' version of the window.setTimeout function.

Output :

The $interval Service

The $interval service is AngularJS' version of the window.setInterval function. It repeatedly executes a function after a specified time interval in milliseconds.

Output :

Create Your Own Service

To create your own service in AngularJS, you use the .service() method and connect it to your module.

Then inject your custom service into a controller or another service to use it.

Output :


Hexadecimal Converter Using Custom AngularJS Service and Filter

This program creates a Hexadecimal Converter where a user can input a number and instantly see its hexadecimal (base-16) equivalent.

  • The raw number entered by the user.
  • The hexadecimal result of that number using a custom filter myFormat.

This program is a Hexadecimal Converter built using AngularJS. It uses a custom service to convert a number into hexadecimal format, and a custom filter to apply that conversion in the view. The user types a number, and the converted result appears instantly.

Output :