Understanding Module Dependency in AngularJS

Module dependency in AngularJS is fairly easy to understand. But a few aspects may not be obvious to the new comers. So, here we go.

Let us say that we have a module called M1 with a directive, service and controller.

angular.module("M1", [])
.directive("simple", function() {
  return {
    template: "Hello Mars"
.factory("mySvc", function() {
  var svc = {};

  svc.sayIt = function(planet) {
    console.log("Hello " + planet);

  return svc;
.controller("ctrl1", function($scope) {
  $scope.message = "Hello Moon";

Next, we create a module called M2 that depends on M1.

angular.module("M2", ["M1"]) //M2 depends on M1
.controller("ctrl2", function($scope, mySvc) {
  $scope.message = "Hello World";
  mySvc.sayIt("Venus"); //Use service from another module

So the controller ctrl2 injects the service mySvc which is available from a different module. This will work out fine since we have declared that M2 depends on M1.

Let’s use controller ctrl2.

<body ng-app="M2">

<div ng-controller="ctrl2">


This will work as expected. We will see:

Hello World.

The console will show “Hello Venus”.

Now, here’s something that may not be obvious. You can use any directive and controller from module M1 within the boundary of M2. For example:

<body ng-app="M2">

<div ng-controller="ctrl2">

<div ng-controller="ctrl1">

<div simple></div>

All of this will work out just fine. We will see:

Hello World
Hello Moon
Hello Mars

Practical Use

By default, AngularJS can bootstrap only one module per page. This may appear problematic in complex pages that aggregate many different distinct features. That is fine. Use a single ng-app in the page. But make that module depend on other modules. Now you can use the directives and controllers from all modules in the dependency chain.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.