简体   繁体   中英

How do I know what dependencies I can inject into a controller?

I am trying to use $routeProvider dependency inside my controller:

.controller('mainController', function($scope, $state, $routeProvider) {

But I am getting the error:

Error: [$injector:unpr] Unknown provider: $routeProviderProvider <- $routeProvider

How do I know what dependencies I can inject into any given controller?

You can only access services in the controller not the providers so use $route here.

Therefore you are getting error $routeProviderProvider becuase it is looking for the provider for $routeProvider which is itself a provider for $route .

Docs

There are two phases inside angular

  1. Configuration Phase (Here we use app.config to write a code)
  2. Run phase (Where we use app.run , after run cycle all other directives gets executed using compile cycle)

Provider is nothing but service/factory but the most important thing is it can be accessible inside configuration phase.

Example

Suppose we have below provider

myApp.provider('unicornLauncher', function UnicornLauncherProvider() {
    var useTinfoilShielding = false;

    this.useTinfoilShielding = function(value) {
        useTinfoilShielding = !!value;
    };

    this.$get = ["apiToken", function unicornLauncherFactory(apiToken) {
        return new UnicornLauncher(apiToken, useTinfoilShielding);
    }];
});

While inject it inside config you should always prefix it Provider like unicornLauncherProvider

While using it inside controller you could use it as unicornLauncher

Note:

Provider are always accessible inside .config ( configuration ) phase with suffix Provider in their name, While inside controller you could > directly inject it using unicornLauncher (direct provider name)

Services/Factory They are not visible in config phase of angular

Still confuse then do refer this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM