AngularJS Modules

An AngularJS module is the container that defines an application and groups its controllers, services, filters, and directives together.

What Is a Module?

In AngularJS, a module is a container for the different parts of an application, such as controllers, services, filters, and directives. The module is also the entity that ties your application to a specific HTML element with the ng-app directive.

You create a module by calling angular.module() and passing it a name and a list of dependencies. An empty array means the module does not depend on any other modules.

Creating a Module

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

<script>
var app = angular.module("myApp", []);
</script>

</body>
</html>

Once a module is created, connect it to your HTML using ng-app, matching the module name exactly.

Connecting a Module to HTML

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

<div ng-app="myApp">
  <p>{{ 5 + 5 }}</p>
</div>

<script>
  var app = angular.module("myApp", []);
</script>

</body>
</html>

The Dependency Array

The second argument to angular.module() is an array of other modules this module depends on. Passing an empty array creates a brand-new module. Passing existing module names (like ["myApp"]) lets you retrieve and extend an already-defined module rather than redefining it.

  • angular.module("myApp", []) — creates a new module named myApp.
  • angular.module("myApp") — retrieves the existing myApp module (no array argument).
  • angular.module("myApp", ["ngRoute"]) — creates myApp and declares a dependency on the ngRoute module.
Note: Calling angular.module("myApp", []) more than once will overwrite the module and remove anything already registered on it. Use angular.module("myApp") without the array to fetch it again in another file.

Why Modules Matter

Modules keep applications organized and make code reusable across projects. A large application is typically split into feature modules (for example, a module for the customer area and another for the admin area), which can then be combined into a single root module.

PieceRegistered On the Module Via
Controller.controller(name, constructor)
Service.service(name, constructor) / .factory(name, fn)
Filter.filter(name, fn)
Directive.directive(name, fn)
Note: Every AngularJS app needs exactly one module referenced by ng-app, even if that module simply depends on several smaller ones.

Exercise: AngularJS Modules

What does the array in angular.module('myApp', []) represent?