Francis Ducharme Francis Ducharme - 5 months ago 13
AngularJS Question

Dependency injection hell, what is expected?

I'm trying to separate components into several files for a simple application but angular's dependency injector is giving me headaches and I don't really know what is expected.

Unknown provider: servicesProvider <- services <- maincontroller


Is the error I'm getting.

app.js

//Application definition with injected dependencies
var app = angular.module('leadcapacity', ['services', 'utils', 'customfilters', 'controllers']);


services.js

var services = angular.module('services', []);

services.service('xrmservice',
[
'$http', function($http) {

var oDataUrl = Xrm.Page.context.getClientUrl() + '/XRMServices/2011/OrganizationData.svc/';
var service = {};

service.query = function(entitySet, query) {
return $http.get(oDataUrl + entitySet + '?' + query);
};

return service;
}
]);


controllers.js

var ctrls = angular.module('controllers', ['utils', 'services']);

ctrls.controller('maincontroller',
function ($scope, services, utils) {



};
});


And the include order in
index.html


<script src="service.js"></script>
<script src="controllers.js"></script>
<script src="app.js"></script>


Looks fine to me. I know this is perhaps not the best way to organize things, but getting a "Hello world" first would be nice.

Thanks.

Answer

Error message appearing in console clearly says that, services dependency isn't exists in the module.

You have injected incorrect service name in maincontroller controller factory function, basically you were trying to to inject services(module name) instead of xrmservice(service name)

function ($scope, services, utils) {

should be

function ($scope, xrmservice, utils) {

Additional

Do follow Inline Array annotation of DI, as you were already used the same in your xrmservice service JS file, so that in future you don't need to go back and change that when you face javascript minification related issues.

Controller

ctrls.controller('maincontroller', [ '$scope', 'xrmservice', 'utils',
    function ($scope, xrmservice, utils) {

         //code goes here
         //....
    };
}]);
Comments