3

I'm a little confused about how modules load in angular. Take for example the following code:

var app = angular.module("app", [ "app.widgets", "app.core"]);


    var core = angular.module("app.core", []);
    core.factory("foo", function(){
      return {
        ping: function(){
         return "pong";
        }
      }
    });

    var widgets = angular.module("app.widgets", []);
    widgets.controller("WidgetController", function($scope, foo){
      $scope.items = [1,2,3,foo.ping()];
    });

<body ng-app="app">
  <ul ng-controller="WidgetController">
    <li ng-repeat="item in items">
      {{item}}
    </li>
  </ul>
</body>

I'm confused as to how my "app.widgets" module has access to the "app.core" module even though it wasn't declared as a dependency.

It seems to be picking up the dependency because both "app.widgets" and "app.core" are declared in a third module--- which is very convenient. But it doesn't seem very intuitive to me.

So I guess my question is "will two modules 'know' about each other if they are declared in a third module?". And is that documented behavior?

ek_ny
  • 10,153
  • 6
  • 47
  • 60

2 Answers2

3

You have included two modules i.e. [ "app.widgets", "app.core"] into your app module, and then you are using the WidgetController inside the app. Though you don't make any explicit dependency for app.widgets module, you can still access the factory foo from module app.core inside app module because your app module depends on app.core. If you try ,

<body ng-app="widgets ">
  <ul ng-controller="WidgetController">
    <li ng-repeat="item in items">
      {{item}}
    </li>
  </ul>
</body>

This wont work, because there will be nothing like factory foo defined in your ng-app="widgets". So for understanding, think of the app module as container for both your modules [ "app.widgets", "app.core"] in which you can access all the controllers ,factories,etc as if they were part of the app module itself.

Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88
2

I think it goes like this:

1) "app" has "app.core" injected, so all "app.core" services, factories etc. are available for "app" module.

2) into "app" module you also inject "app.widgets", which then gets access to everything "app" module has access to.

So: app gets access to app.core && app.widgets get access to app -> app.widgets get access to app.core

I'm not sure if it's documented somewhere, if it is, I'd love to read it. Check out this script for more fun stuff:

http://plnkr.co/edit/Z8cZHJTekUa68eXuiCmW?p=preview

It seems that foo declared on the parent module is not overriden by foo's from child modules. If injected modules both have foo, the latter is used:

var app = angular.module("app", [ "app.core", "app.widgets"]);

Makes app.widgets.foo the app.foo and app.core.foo. It overrides app.core.foo!

kihu
  • 842
  • 5
  • 13