Why and When to Use and Create AngularJS Services and Modules

Services are used to encapsulate functionality that you want to reuse in an application but that don’t fit neatly into the Model-View-Controller pattern that I described in Chapter 3. Services are commonly used to implement cross-cutting concerns, which is a catchall term for any functionality that is affected by more than one component or affects more than one component. Typical examples are logging, security, and networking. They are not part of the model (unless your business is logging, security, or networking), they don’t belong to the controllers because they don’t respond to user interaction or perform operations on the model, and they are not part of the view or a directive because they don’t present the model to the user. In short, if you need to create functionality that doesn’t go elsewhere, then you create a service.

Modules have two roles in AngularJS. The first is they define the application functionality that is applied to the HTML elements using the ng-app directive. I have done this in every example application in this book, and defining a module is the starting point for AngularJS development. The second use of a module is to define functionality, such as services, directives, and filters, in a way that makes it easy to reuse it in different applications. Table 18-2 summarizes why and when to create services and modules.

AngularJS includes a number of built-in modules services that provide important functionality. In this chapter,

I’ll show you the different ways to create and use modules and services before describing the built-in services in depth in the following chapters.

Source: Freeman Adam (2014), Pro AngularJS (Expert’s Voice in Web Development), Apress; 1st ed. edition.

Leave a Reply

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