Angular JS- Working with different modules

By considering that every element in Angular is a module we can use different modules to subdivide our components. We can also let Angular keep the links between them, without needing to store a global variable for the app.

<!DOCTYPE html>
<html xmlns=""><head>
    <title>Angular JS</title>
<body data-ng-app="myApp">
    <div data-ng-controller="myController1">
        <p>The full name is {{ firstName + " " + lastName }}</p>
    <div data-ng-controller="myController2">
        <p>The full name is {{ firstName + " " + lastName }}</p>
    <script src="//"></script>
    <script src="//"></script>
        angular.module("myApp", ["myApp.controllers"]);
        angular.module("myApp.controllers", []);
        angular.module("myApp.controllers").controller("myController1", function ($scope) {
            $scope.firstName = "John";
            $scope.lastName = "Doe";
        angular.module("myApp.controllers").controller("myController2", function ($scope) {
            $scope.firstName = "Tizio";
            $scope.lastName = "Caio";

We are just using the Angular global reference to create 2 modules. We can look at modules as a kind of logic containers for Angular elements, more or less as namespaces. Modules are very flexible and is up to us to choose how to use them to subdivide our application.

In this case the first module “myApp” represent the app entry point and we use it to refer the other modules as dependencies (inside the second parameter). The second module “myApp.controllers” (the name is just a convention) is the container in which we will put the controllers (we will use the controller() method to do this).

A new module is created when we use the module() method with both the name and the dependencies as parameters. To simply refer an already created module we must use the module() method with just the name parameter. This is what we are doing on the subsequent instructions to append our controllers to the “myApp.controllers” module with the controller() method.

When previously we were using a global variable for the app and we were adding our controllers to it we was basically using a single module with a global reference, just to be able to refer it from different files. In this case we are taking advantage from Angular itself, that can do the job for us.

Is important to notice that subdivision by modules mustn’t necessarily reflect the physical subdivision of the components between files. Also in this way modules can be considered similar to namespaces.


Leave a Reply

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

You are commenting using your 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