What is Angular JS Service?
A service is a function/object, that is available for and limited to your AngularJS application.
Angular JS has 30 built-in services.
The $location service is one of them and it has methods which return information about the location of the current web page:
You can use $location service in a controller:
Noted: $location service is passed in to the controller as an argument. In order to use the service in the controller, it must be defined as a dependency.
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 common used services in AngularJS applications. The service makes a request to the server, and lets your application handle the response.
Use the $http service to request data from the server:
This example demonstrates a very simple use of the $http service. Learn more about the $http service in the AngularJS Http Tutorial.
The $timeout Service
The $timeout service is AngularJS' version of the window.setTimeout function.
Display a new message after two seconds:
The $interval Service
The $interval service is AngularJS' version of the window.setInterval function.
Display the time every second:
Create Your Own Service
To create your own service, connect your service to the module:
Create a service named hexafy:
To use your custom made service, add it as a dependency when defining the controller:
Use the custom made service named hexafy to convert a number into a hexadecimal number:
Use a Custom Service Inside a Filter
Once you have created a service, and connected it to your application, you can use the service in any controller, directive, filter, or even inside other services.
To use the service inside a filter, add it as a dependency when defining the filter:
The service hexafy used in the filter myFormat:
Required fields are marked *
Get all latest content delivered to your email free.