leaksterrr
leaksterrr

Reputation: 4167

$injector unable to resolve required dependency

I'm trying to get into the habit of structuring my Angular projects following LIFT protocol (Locate, Identify, Flat, Try(Dry)) but I'm having some difficulty resolving dependencies from other files.

I have the following factory:

(function () {

    'use strict';

    angular
        .module('CBPWidget', [])
        .factory('apiManufacturers', apiManufacturers);

    function apiManufacturers () {

        function hello () {
            return 'hello';
        }

        return {
            hello: hello
        };

    }

})();

and the following controller:

(function () {

    'use strict';

    angular
        .module('CBPWidget', [])
        .controller('stepOneController', stepOneController);

    stepOneController.$inject = ['$scope', 'apiManufacturers'];

    function stepOneController ($scope, apiManufacturers) {

        $scope.step = 'step1';
        console.log(apiManufacturers.hello);

    }

})();

and the following error is thrown:

Error: [$injector:unpr] Unknown provider: apiManufacturersProvider <- apiManufacturers <- stepOneController

My factory JS file is placed above the controller JS file in my HTML (which will be minified).

Any advice on where I'm going wrong would be greatly appreciated as I'm new to structuring projects this way.

Upvotes: 0

Views: 1063

Answers (3)

Shripathi Kamath
Shripathi Kamath

Reputation: 321

From the documentation for AngularJS, you'll find that

.module('CBPWidget', [])

is different from

.module('CBPWidget')

The latter is what you need to refer to a module, the former is for defining one. In all cases except where you first define it, you should be using the latter form.

Upvotes: 0

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

Your angular.module('CBPWidget', []) block code is redefining angular app, which was flushing apiManufacturers service associated with it, & it is defining controller in it. You should never do that, you should use existing module which was already defined.

Code

angular
        .module('CBPWidget') //don't overide app here use existing
        .controller('stepOneController', stepOneController);

Upvotes: 0

Mukund Kumar
Mukund Kumar

Reputation: 23221

Here you are creating CBPWidget module two times. angular.module('CBPWidget',[]) is used for creating module and angular.module('CBPWidget') is used for getting already created module. so replace controller code with this :

(function () {

    'use strict';

    angular
        .module('CBPWidget')//now you are getting CBPWidget module
        .controller('stepOneController', stepOneController);

    stepOneController.$inject = ['$scope', 'apiManufacturers'];

    function stepOneController ($scope, apiManufacturers) {

        $scope.step = 'step1';
        console.log(apiManufacturers.hello);

    }

})();

Upvotes: 2

Related Questions