Sharing Top Content from the Angular-sphere.

Dev Guide: Understanding Dependency Injection · angular/angular.js Wiki · GitHub

  • Defining a provider is done via the method on the service, and you can get hold of the service by asking for it to be injected into an application’s function.
  • An example might be something like this: – – Here we’ve defined a new provider for a service called ; we can inject a variable named into any injectable function (like controllers, more on that later) and Angular will call the provider’s function in order to return a new instance…
  • For example, since we always return the same function for our service, we can use to define it, too: – – Again, this is 100% identical to the other two methods we’ve used to define this function–it’s just a way to save some typing.
  • Now we have a function on our provider called that we can use to customize our ; we can get access to this provider in a block to call this method and customize the service.
  • For example, when you define a controller like this: – – What you’re actually doing is this: – – Later, when Angular needs to create an instance of your controller, it uses the service (which in turn uses the to invoke your controller function so it gets its dependencies injected…

angular.js – AngularJS – HTML enhanced for web apps!

Dependency injection in AngularJS is supremely useful, and the key to making easily testable components. This article explains how Angular’s dependency injection system works.

The service is responsible for telling Angular how to create new injectable things; these things are called services. Services are defined by things called providers, which is what you’re creating when you use . Defining a provider is done via the method on the service, and you can get hold of the service by asking for it to be injected into an application’s function. An example might be something like this:

Here we’ve defined a new provider for a service called ; we can inject a variable named into any injectable function (like controllers, more on that later) and Angular will call the provider’s function in order to return a new instance of the service. In this case, the thing that will be injected is a function that takes a parameter and s a message based on the name. We might use it like this:

Now here’s the trick. , , and are all just shortcuts to define various parts of a provider–that is, they provide a means of defining a provider without having to type all that stuff out. For example, you could write that exact same provider just like this:

It’s important to understand, so I’ll rephrase: under the hood, AngularJS is calling the…

Dev Guide: Understanding Dependency Injection · angular/angular.js Wiki · GitHub