Search code examples
angularjsangularjs-controllerangularjs-factoryangularjs-injector

angularjs - accessing a factory from a controller in another module


This is the factory code under the myApp module

angular.module('myApp')
        .factory('userFactory', ['$http', function ($http) {

            var userFactory = {};

            userFactory.login = function (user) {
                return $http.post(sc.getDomain() + 'session/create', user);
            };

            return userFactory;
        }]); 

and the controller is under the myApp.user module

angular.module('myApp.user',[])

.controller('loginCtrl', ['$scope', function ($scope) {

}]);

and this is the main app level module with myApp.user injected -

angular.module('myApp', ['ngRoute','myApp.user']). //etc

How would I access the factory in the "myApp" module from the controller which is in the "myApp.user" module?


Solution

  • myApp.user depends on myApp. So myApp should be set as a dependency of myApp.user instead.

    However, this will probably not end up in clean code and I'm not sure how circular dependencies are handled. You should move the userFactory to myApp.user instead.