angularjsdependency-injectionangularjs-moduleangularjs-injector

Difference between module dependency and service dependency in AngularJS


I don't understand what's the difference between module dependency and service dependency. For example,

angular.module('components.users', [])
    .controller('UsersController', function(Users) {
        //...
}) 

angular.module('api.users', [])
  .factory('Users', function() {
        //...
});

I don't understand why Users service could be passed in in controller method of components.users as no module is required by component.users module. (I thought api.users module should be passed in in the module method as one of required modules).

In other words...

What is difference between module dependency and service dependency?

Why a service is available even when the module it is defined is not required?


Solution

  • You may check if you're using an existing code base from your team that they have defined a root or base 'app' module that includes your defined 'Users' service. Below is an example of how this may be working in your project and why you're able to use the 'Users' service:

    <!DOCTYPE html>
    <html ng-app="app">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <div ng-controller="controller">
            {{ text }}
        </div>
        <script src="angular.js"></script>
        <script type="text/javascript">
        angular.module('services',[])
            .factory('service',function(){
                return {
                    text: "this is a string value defined in a service."
                }
            })
        ;
        angular.module('controllers',[])
            /*
              Here the service "service" is being used however
              has not been specified in it's containing module.
            */
            .controller('controller',function($scope,service){
                $scope.text = service.text;
            });
        ;
        /*
          The above works because in some way all services and controllers
          have been defined. In this example by manually specifying each.
        */
        angular.module('app',['services','controllers']);
        </script>
    </body>
    </html>