What's wrong with this factory dependencies issue?

62 Views Asked by At

I'm working with AngularJS. I'd like to get a controller using a first factory which using another one.

It could be schematize like that:

MyCtrl -> Factory1 -> Factory2 

So I tried to do in 3 different files (loaded in the following order):

Factory2.js

app.factory('Factory2', function () { ... })

Factory1.js

app.factory('Factory1',['Factory2', function (Factory2) { ... })

controller.js

app.controller('MyCtrl',['$scope', 'Factory1', function ($scope, Factory1) { ... })

And in my HTML I have:

<script src="services/factory2.js" type="text/javascript"></script>  
<script src="services/factory1.js" type="text/javascript"></script>
<script src="controllers/controller.js" type="text/javascript"></script>

But it doesn't work and I've got this error Unknown provider: Factory2Provider <- Factory2 <- Factory1

What's wrong with my code? Am I missing something?

2

There are 2 best solutions below

0
On BEST ANSWER

You can refactor your codes and use modules, in this way you will not need to use $inject

var app = angular.module('app', ['factories', 'mymodule']);

angular.module('factories', [])
    .factory('Factory2', function () { })
    .factory('Factory1', ['Factory2', function (Factory2) {
         return myCustomFunction = function () {
             alert('todo');
         }
    }]);

angular.module('mymodule', [])
    .controller('MyCtrl', ['$scope', 'Factory1', function ($scope, Factory1) {
    $scope.text = "testing";
}])

http://jsfiddle.net/kL78rdr3/3/

5
On

Why don't you use explicit injection with $inject? It is a better approach, because it gives you more control over the dependencies. For example:

userController.js

function userController (model, routeParams, searchService) {
    //implementation
}
userController.$inject = ['$scope', '$routeParams', 'searchService'];
app.controller("userController", userController);

searchService.js

var searchService = function (http, log) {
    //implementation
}
searchService.$inject = ["$http", "$log"];
app.factory("searchService", searchService);

This post may be useful: Explicit Dependency Injection