Chapter 7. Services, Filters, and Components
The easiest part to learn for a new developer is creating views and controllers in Angular. In fact, complicated, wholly functional applications can be written using only views and controllers, but there are often better ways to organize your code using Angular’s other components.
Before diving into refactoring controllers, it’s helpful to understand the role that services, filters, and directives play in creating clean Angular applications. Controllers with too many responsibilities are often doing work better handled by another component type. First, it’s helpful to understand what these components are for and why they are helpful in our refactoring efforts.
Services are components that don’t interact with the DOM but are useful for encapsulating state and business logic. Services can be used to manage loading, saving, and modifying data. Services are injectable components, which makes them easy to test. Angular has built-in services like $http
for making AJAX calls and $location
for interacting with the browser’s address bar. Services are fundamental to building modular, well-separated applications.
Filters are transformation functions that are available globally within Angular templates. Filters are useful when data needs to be displayed to the user in a format that’s different from its data model. For example, an internal representation of a phone number may be ten digits, but a filter can be used to display it in the template ...
Get Refactoring Angular Applications 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.