0

Note: I'm not seeking the differences between the value, factory, service, and provider 'recipes', as explained here.

I'm looking for clarification on the different ways to define them: Correct me if I'm wrong, but it appears as though

myApp = angular.module('myApp', [])
    .value(...)
    .factory(...)
    .service(...)
    .provider(...)

map to

$provide.value()
$provide.factory()
$provide.service()
$provide.provider()

And you can use either way. I asked this question, and realize I can use $provide as a dependency to module().config(). My questions:

  1. When/why would I use angular.module().provider() vs using the $provide dependency?
  2. Is there any way (or reason) to access/change a provider after definition?
  3. Using AngularJS Batarang for Chrome, I'm looking at the various angular $scope properties, and don't see $provide or $injector. Where do these live?
Community
  • 1
  • 1
Michael Lewis
  • 4,252
  • 6
  • 28
  • 39
  • 1 - You use the first when you can use it directly and the other when you can't, that's why angularJs use dependency injection, there is no mystery about it, i think. 2 - Yes, there is and not only for provider, that's why AngularJs is focused in dependency injection. 3 - I don't know. – Rodrigo Fonseca Feb 07 '14 at 17:53

1 Answers1

1
  1. The provider methods off the module definition are just short cuts. Use them as often as you like because it leads to shorter, easier to read and understand code. Less ritual/ceremony is involved than injecting the $provider service and calling that directly. The main reason to use $provide directly is to access a method on it that is not a short cut from module (such as the decorator) or if you have to do something from within a service or component that is not up at the module definition level.

  2. The common case for changing a provider after it's definition is when you are integrating a third-party component and want to add or change the behavior. The third-party module will define the service and then you step in and override or extend it in some way that is specific to your app. A common case for example is to take the built-in Angular exception handler and extend that to interface with your own components.

  3. $scope is a special "glue" used for data-binding and only exposes properties/functions that you explicitly set on the $scope. All of the other miscellaneous modules/services are stored within Angular's dependency injection container. The very first thing Angular does is create an $injector instance to keep track of dependencies. Therefore $injector === $injector.get('$injector'). Same with $provide. Anything prefixed with a $ is by convention a service that Angular places in the $injector for you to use.

Jeremy Likness
  • 7,531
  • 1
  • 23
  • 25