Search code examples
javascriptangularjsdependency-injectionangularjs-controllerangularjs-provider

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?


Solution

  • 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