AngularJS Tutorial for Beginners 4 – AngularJS Modules and Controllers

In this AngularJS Tutorial we would examine the various aspects of an AngularJS program.


We would cover the following topics:

  1. What is a Module in AngularJS?
  2. How to Create a Model
  3. What is a Controller in AngularJS?
  4. How to Create a Controller
  5. How Register a Controller with a Module


These are called directives the three most important bit of an AngularJS application that we used in out program. We would discuss more on directives in Tutorial 5.


1. What is a Module in AngularJS?

A module in AngularJS is a container that holds various parts of an AngularJS application such as controller, directives, services and filters. It serves  as the entry point to the application.
A module specifies how the AngularJS starts.
A module is the first thing you create in an AngularJS application.


2. How to Create a Module

To create a module, use the AngularJS syntax below and specify the name of the module just like we did in Tutorial 2 and Tutorial 3.


var FirstApp = angular.module('FirstApp', []);


In creating a module, you specify two parameters:

  • the name of the module
  • array of dependencies the module depends on. In this case we pass an empty array [ ] showing that our module does not depend on any external dependencies.


3. What is a Controller?

The next thing you create after creating a module, is a controller.
A controller in AngularJS is function that controls the communication between the application logic and the view. For example, a controller would manage retrieving data from the database and displaying it in a html page.


4. How to Create a Controller

To create a controller, simply create a function and assign it to a variable as shown below


var MyController = function($scope) {
 $ = "Welcome to AngularJS";


In this controller, we pass a parameter called $scope to the controller function. $scope is used to make variables available in the view. So any variable attached to the $scope is accessible from the view using the binding expression {{  }}.
In this example, we can access the variable name from the html page using {{ name }}


5. How to Register a Controller With a Module

The next step after creating a module and a controller is to register the controller with a  module.
To register a controller with a module, use the syntax below:


FirstApp.Controller("MyController", MyController);


Now That we have created a module and a controller, and registered a controller with a module, we can now move to the next step and that is how to use the module and controller in a view.
For this we need to discuss AngularJS directives in Tutorial 5.