2

Consider the following code:

angular.module('app', ['app.core'])
    .factory('NameService', function() {
        return {
            getName: function() { return 'Omar' ;}
        };
    });
       

angular.module('app.core', [])
    .controller('MainController', function($scope, NameService) {
        $scope.name = NameService.getName();
    });
<body ng-app="app">
    <div ng-controller="MainController">
        {{name}}
    </div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
</body>

The result displays "Omar". Note, however, that the NameService is defined in the app module which is not a dependency of the app.core module. I understand depending on each other would be circular but why does this work?

0

2 Answers 2

4

Essentially, every angular application has a single $injector. When a dependency is registered, it's signature is added to the $injector.modules Array. When a specific dependency is invoked, it's signature is retrieved from the array. The $injector does not restrict access to the modules array based on where the registration originated from; any registered dependency is available everywhere in the application.

Sign up to request clarification or add additional context in comments.

Comments

2

It's a design flaw in Angular 1.x. It works because Angular keeps a global registry of all services, controllers, factories, directives, and so on. "Installing" a module means putting all its contents into the global registry, using their name as a string key. So a module can still work if it does not register its dependencies, as long as some other module does.

This is actually a pretty common source of errors in large Angular applications, because you can end up using undeclared dependencies without knowing it, so reorganising your app's module structure will break things in nonobvious ways.

Angular 2's module system is better in this respect.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.