7 Services, Factories, and Providers
WHAT YOU WILL LEARN IN THIS CHAPTER:
- The basics and benefits of dependency injection
- Inferred, annotated, and inline function annotation
- Tying your services into the dependency injector
- The three ways to create a service
- Common use cases for services
- Using providers to configure AngularJS
WROX.COM CODE DOWNLOADS FOR THIS CHAPTER
You can find the wrox.com code downloads for this chapter at http://www.wrox.com/go/proangularjs
on the Download Code tab.
AngularJS is roughly equal parts library and framework. In addition to providing you with sophisticated tools, it provides a structure for organizing your code. In particular, AngularJS’s dependency injection supplies a framework for writing code that is highly reusable, highly modular, and easy to unit test. If you’ve written an AngularJS controller before, you’ve used dependency injection. For instance, in the next example, $scope
and $http
are services that the dependency injector passes to the MyController
function:
function MyController($scope, $http) {
// Code here
}
You may have taken it for granted that AngularJS does some magic to pass the right parameters to MyController
so that you can access the correct $scope
and make HTTP requests with $http
. This particular magic is known as dependency injection, and $scope
and $http
are services. A service is some JavaScript variable uniquely identified by its name that the dependency injector knows about. Factories and providers ...
Get Professional AngularJS 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.