AngularJS Services

AngularJS provides a rich set of built-in services.These are basically singleton objects in Angular JS used to share the common logic across the application.AngularJS built-in services are all prefixed with ‘$’ sign.


AngularJS Services are:

Lazy Instantiated – Service gets instantiated only when the application component depends on it.

Singleton – Service is instantiated when it is called for the first time(When it is injected for the first time) and its reference is used by all the components instead of instantiating again and again.Hence these are angular singletons.


AngularJS Built in Services:

$scope  – Service used for binding model data in the controller with the view.It’s gets instantiated when passed as an argument to the controller.


$scope.functionName = function(){


$http – Facilitates communication with the remote HTTP server via the browser’s XMLHttpRequest object or via JSON.

$window – It is similar to JavaScript’s window object.In JavaScript it is a global object contains many methods like alert(),prompt() and confirm().Since window object in Javascript is global causes testability problems.In AngularJS $window service is the wrapper around window object, so it is easy to override, remove or mock for testing.


$window.alert("Hello am angularJS service");

$interval – It is a wrapper around JavaScript’s window.setInterval function used to execute the provided function on every delay milliseconds with the specified count(this is optional).If we don’t specify the count it will be executed until we explicitly stop it.



To cancel this service execution we will the promise object returned by it upon every iteration.

var promise = $interval(function,delay);


$timeout – It is a wrapper around JavaScript’s window.setTimeout function used to execute the provided function after a delay of specified milliseconds.Its execution can be canceled by using the returned promise object.


var promise = $timeout(function,delay);


$cookies – Used to read, write or remove the cookies.This feature is available in the angular-cookies.min.js file. 

get(key) - gets the cookie object with the given id.
getObject(key) - gets the deserialized cookie object value with the given id.
put(key,value,[option]) - inserts the given cookie value to the given cookie id(value is the raw and option is an object.
putObject(key,value) - serializes and sets the cookie value to the key(value is the raw value.           getAll() - gets all the key-value cookie objects.
remove(id,[option]) - It removes the specified cookie with the given id.

$filter – Used for formatting data displayed to the user.It can be used with AngularJS built-in filters as well as custom filters.



$document – It is a wrapper around browser’s window.document object.It is a jQuery collection.When $documnet is used it will not directly refer to HTML DOM instead it return jQuery collection it contains objects and properties.



$log – This service is used to write error, info, warning or debug info into browser’s console.It simplifies debugging and troubleshooting easier.


$"Info message");

$log.error("error message");

$log.warn("warning message");

$log.log("log message");

$log.debug("debug message");

$location – Similar to the window.location object it exposes the URL in the browser’s address bar.Any changes in the URL will be reflected into $location service and vice versa.


var absUrl = $location.absUrl();
var protocol = $location.protocol();
var port = $location.port();
var path = $location.path();
var host = $;
var searchObject = $;
var hash = $location.hash();

$parse – It converts AngularJS expression into a function.


var getter = $parse('name');

var setter = getter.assign;

$exceptionHandler – Catches the uncaught exceptions in AngularJS expressions.It further delegates it to the $log.error.This default error can be overridden.



$cacheFactory – Used to construct the objects using key-value pairs.It includes put, get, remove and filter methods to modify the key-value pairs.



$anchorScroll – Enables scrolling to the other part of the page that is specified using $location.hash() function.



$rootElement – AngularJS bootstrap process starts with ‘ng-app’ directive which is a root element.This root element can be declared on any DOM element.This can be accessed using $rootElement.


$scope.element = $rootElement.attr("ng-app");
Custom Services

For memory and performance reasons, controllers are instantiated whenever they are required and removed when they not. That is whenever a new route loads, the existing controller will be removed.

Once AngularJS services are registered they stay lifetime of the app and enables data sharing between controllers.

An AngularJS service can be created or registered in five different ways,

  • Using the service() method
  • Using the factory() method
  • Using the value() method
  • Using the constant() method
  • Using the provider() method

Using the service() method



Every service must be registered with the application module.Let’s create a simple calculator service.

<!DOCTYPE html>
<title>Service example</title>
<script src="calculator.js"></script>
<body ng-app="calApp" ng-controller="calController" ng-style="resultStyle">
<header> Calculator </header>
<table align="center">
<tr><input type=text col-span="2" placeholder="0" ng-model="result" ></tr>
<td><input type=button value="sqrt" ng-click="sqrt()"></td>


var app = angular.module("calApp", []);
app.controller("calController", ['$scope','calService', function($scope,calService){
 $scope.resultStyle = { "text-align":"center","margin":"10%"};
 $scope.sqrt = function(){
 $scope.result = calService.squareOfNumber($scope.result);

app.service("calService" , function(){
this.result = -1;
this.squareOfNumber= function(number){
result = number*number;
return result;

Here if we notice that service returns an instance of the constructor function.The service is injected into the controller by using dependency injection mechanism.

Try It!

Using the factory() method

Let’s verify the same example using factory service.




var app = angular.module("calApp", []);
app.controller("calController", ['$scope','calService', function($scope,calService){
  $scope.resultStyle = { "text-align":"center","margin":"10%"};
  $scope.sqrt = function(){
  $scope.result = calService.squareOfNumber($scope.result);

//factory example
app.factory("calService" , function(){
  var obj = {};
    obj.result = -1;
    obj.squareOfNumber = function(number){
       result  = number*number;
       return result;
    return obj;

Here while injecting the factory we will be provided with the value returned by the passed function reference as an instance.

Try It!

Using the value()/constant() method

An ideal way to share data application wide is by value() and constant() services and provide a global data without polluting the global namespace.These can be injected into the controllers or other services similar to $scope service.The only difference between the two is constant() can be injected into config() component as well.




Here option parameter can be any data type like String, Object or Number.

Using the Provider() method

Provider services can be passed to config() method unlike Service() and Factory() methods.Providers are responsible for instantiating various dependencies used by our application.For Example, $http and $route dependencies will be instantiated by the AngularJS built-in providers $httpProvider and $routeProvider.

Since providers are singletons they are asked to provide the object only once, later that will be stored in AngularJS injector service and provided by it whenever passed as a dependency.

Providers can be defined in the same way as Service() and Factory().Here, the function takes ‘$get’ property that is used to instantiate the requested object.

NOTE: When Provider is passed as an argument to the config() method that should be appended with Provider keyword.


Leave a Reply

Your email address will not be published. Required fields are marked *