AngularJS built-in services and how to use them

Services in AngularJS provide a method for us to keep data around for the lifetime of the app and communicate across controllers in a consistent manner. Services are singleton objects that are instantiated only once per app (by the $injector) and lazyloaded (created only when necessary).

Read more about Services : Understanding Services in AngularJS

Following is the list of commonly used in-built services of AngularJS:

$cookiesUseful to write, read and delete browser cookies.
$windowProvides a reference to the browser’s window object.
$filterProvides the ability to filter data.
$documentThis service is a wrapper around the browser’s window.document object.
$locationSimilar to window.location object but aditionally exposes the current URL.
$logProvides us the ability to write error, info, warning and debugging information on to the browser’s console.
$parseThis service is useful to convert AngularJS expression into a function.
$timeoutThis service is a wrapper around window.setTimeout function.
$intervalThis service is similar to JavaScript’s window.setInterval function.
$exceptionHandlerThis service is useful to handle uncaught exceptions in angular expressions by overriding the default exception handler behaviour.
$templateCacheUseful to cache the templates
$cacheFactoryFactory that constructs Cache objects and gives access to them.
$anchorScrollWhen called, it scrolls to the element related to the specified hash or (if omitted) to the current value of $location.hash()
$rootElementThe root element of Angular application. This is either the element where ngApp was declared or the element passed into angular.bootstrap.
$rootScopeEvery application has a single root scope. All other scopes are descendant scopes of the root scope.
$sceProvides Strict Contextual Escaping services to AngularJS.

$cookies

The AngularJS $cookies service is used to read, write and delete browser cookies.

Following is a list of methods available under this service:

get(key)Returns the value of a given cookie key. Where key is id of the cookie to be looked up.
getObject(key)This method returns the deserialized value of given cookie key.
put(key, value, [options])This method is used to set a value for given key.
putObject(key, value, [options])This method serializes and sets value for a given cookie key. key is id, value is raw value to be stored and options is an object.
getAll()Returns a key value object with all the cookies.
remove(key, [options])This method is used to remove a cookie based on its key.

Example

$window

A reference to the browser’s window object. While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In angular we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.

Example

$filter

Filters are used for formatting data displayed to the user.

The general syntax in templates is as follows:

Example

$document

A jQuery or jqLite wrapper for the browser’s window.document object.

Example

$location

The $location service parses the URL in the browser address bar (based on the window.location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.

Example

$log

The AngularJS $log service is used to write error, info, warning and debugging information on to the browser’s console. The main purpose of this service is to simplify debugging and troubleshooting.

Example

$parse

The AngularJS $parse service is used to convert AngularJS expressions into a function. $parse takes AngularJS expression as a parameter and converts it into a function.

Example

$timeout

Angular’s wrapper for window.setTimeout. The function is wrapped into a try/catch block and delegates any exceptions to $exceptionHandler service. The return value of calling $timeout is a promise, which will be resolved when the delay has passed and the timeout function, if provided, is executed. To cancel a timeout request, call $timeout.cancel(promise).

Example

$interval

Angular’s wrapper for window.setInterval. The function is executed every delay milliseconds. The return value of registering an interval function is a promise. This promise will be notified upon each tick of the interval, and will be resolved after count iterations, or run indefinitely if count is not defined. The value of the notification will be the number of iterations that have run. To cancel an interval, call $interval.cancel(promise).

Example

$exceptionHandler

Any uncaught exception in angular expressions is delegated to this service. The default implementation simply delegates to $log.error which logs it into the browser console.

Syntax

$templateCache

The first time a template is used, it is loaded in the template cache for quick retrieval. You can load templates directly into the cache in a script tag, or by consuming the $templateCache service directly.

Example

Adding via the script tag:

Adding via the $templateCache service:

To retrieve the template later, simply use it in your HTML:

or get it via Javascript:

$cacheFactory

Factory that constructs Cache objects and gives access to them.

Example

$anchorScroll

The AngularJS $anchorScroll service can be used in conjunction with hyperlink in mark-up to automatically scroll to other part of the page. This service can be disabled by calling $anchorScrollProvider.disableAutoScrolling().

Example

$anchorScroll

The root element of Angular application. This is either the element where ngApp was declared or the element passed into angular.bootstrap. The element represents the root element of application. It is also the location where the application’s $injector service gets published, and can be retrieved using $rootElement.injector().

Usage

$rootScope

Every application has a single root scope. All other scopes are descendant scopes of the root scope. Scopes provide separation between the model and the view, via a mechanism for watching the model for changes. They also provide event emission/broadcast and subscription facility.

$sce

$sce is a service that provides Strict Contextual Escaping services to AngularJS. Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain contexts to result in a value that is marked as safe to use for that context. One example of such a context is binding arbitrary html controlled by the user via ng-bind-html. We refer to these contexts as privileged or SCE contexts.

Example

 

Leave a Reply

Top