Introduction Of Modules And Controller In AngularJS

Modules

A module is a container for different parts of your Application, i.e controller, services, directives, filters, etc.

You can think of a module as a Main () method, in other types of applications. For example, a Net console application has main method which is the entry point into the application. The responsibility of that main method is to wire all the different parts of the application together. Modulesin angular Js are equivalent to main method. Module declarative specifies how the Angular application should be bootstrapped.

How to create a Module?

We use the angular object’s module () method to create a module. The angular module is, by default, provided by the Angular framework.

  1. var myApp = angular.module("myModule", []);  

You must notice that the module method, which Angular method is providing, has two parameters at this moment. The first parameter specifies the name of module that we are creating while the second parameter is to specify the dependency for this module. A module can be dependent on other modules.

What is controller in Angular?

In Angular, a controller is a Java Script function. The job of controller is to build a model for the View to display. Model is nothing but the data in the real world. Application controller may call web services which retrieve data from database.

How to create a Controller in angular?

It is simple. We create a Java Script constructor function like:

  1. var myController = function ($scope) {  
  2.   
  3. $scope.message = "Angular Js tutorial";  
  4.   
  5. }   
You can see that we are passing $scope. $scope is an angular object that is passed to this angular controller by the angular framework, automatically. We attach this model with this $scope object which, then, will be available in the View. Within the View, we use data binding expression to retrieve the data from $scope object.

How to register a controller with module? 

  1. myApp.controller("myController", myController);  

In the module object myApp, we have controller function. The first parameter is the name for controller and the second is the controller function itself.

I have attached a code file, too. I hope this solution will help you.