Sean Kenny

Angular Modules - Module Not Found

permalink

This little one caught me out for an hour or two. Moving away from the global ‘app’ variable in angularJs, I started using the angular.module syntax:

1
angular.module('UserHandler', [])

The app.js starts things using an IIFE (Immediately Invoked Function Expression):

1
2
3
4
5
6
7
(function() {
  'use strict';

  var app = angular.module('bootstrapper', ['ngRoute']);

  // do other config things with the app like routing, etc.
)();

Then onto my controllers:

1
2
3
4
5
6
7
8
9
(function(app) {
  'use strict';

  app.controller('registrationController', [
    '$scope', function($scope) {
    // registration stuff
    }
  ]);
})(angular.module('bootstrapper', []));  // this is bad
1
2
3
4
5
6
7
8
9
(function(app) {
  'use strict';

  app.controller('signinController', [
    '$scope', function($scope) {
    // sign in stuff
    }
  ]);
})(angular.module('bootstrapper', []));  // this is bad

When I run this, the registrationController is never found. Moving it to be declared after the signinController leads to the signinController never being found. Huh?

The secret is in the array on the angular.module() call. Adding the array tells angular that you want a new angular module which dumps the initial one that you just created for the first controller.

The correct way to create the controllers using this form of controller set up is:

1
2
3
4
5
6
7
8
9
(function(app) {
  'use strict';

  app.controller('registrationController', [
    '$scope', function($scope) {
    // registration stuff
    }
  ]);
})(angular.module('bootstrapper'));
1
2
3
4
5
6
7
8
9
(function(app) {
  'use strict';

  app.controller('signinController', [
    '$scope', function($scope) {
    // sign in stuff
    }
  ]);
})(angular.module('bootstrapper'));

Comments