Chapter 5. All About AngularJS Services

Until now, we have dealt with data-binding in AngularJS. We have seen how to take data from our controllers and get it into the UI, and ensure that whenever the user interacts with or types in any data, we get it back into our controllers. We used and worked with some common directives, and dealt with forms and error handling.

In this chapter, we dive into AngularJS services. By the end of the chapter, we will have a thorough understanding of AngularJS services and get some hands-on experience in using core built-in AngularJS services. After that, we will learn why and when we should create AngularJS services, and actually create a simple service ourselves.

AngularJS Services

AngularJS services are functions or objects that can hold behavior or state across our application. Each AngularJS service is instantiated only once, so each part of our application gets access to the same instance of the AngularJS service. Repeated behavior, shared state, caches, factories, etc. are all functionality that can be implemented using AngularJS services.

Service Versus Service

In AngularJS, when we say service, we are actually referring to the conceptual service that is a reusable API or substitutable objects, which can be shared across our applications. A service in AngularJS can be implemented as a factory, service, or provider.

This is one of the badly named concepts in AngularJS and thus can lead to confusion. We end up calling all of the above services. We ...

Get AngularJS: Up and Running now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.