AngularJS Modules and Controller

AngularJS Modules

A module defines an application. It is container for the different parts of your application like controller, services, filters, directives etc.

Controller always belong to a module.

Creation of a module

A module is created by using the AngularJS function angular.module

module

The “myApp” parameters refers to an HTML element in which the application will run. Now we can add controllers, directives, filters, and more, to your AngularJS application.

AngularJS Controllers

AngularJS application mainly relies on controllers to control the flow of data in the application. A controllers is defined using ng-controller directive. A controllers is a JavaScript object containing attributes/properties and functions. Each controller accepts $scope as a parameter which refers to the application/module that controller is to control.

Example:

In the following example we will explain module and controller.

 controller

Output:

 controleroutput

Code Explanation:

  • ng-app directive is used to denote that this application should be considered as an angular application. “myApp” is the name given to our AngularJS application.
  • In body tag we have added an ng-controller directive along with the name of our controller “myControl”. This basically makes our body tag the ability to access the contents of the “myControl”. We need to mention the name of the controller under the directive to ensure that we are able to access the functionality defined within the controller.
  • We are creating a module which will attached to our “myApp” So this module now becomes part of our application.
  • In the module, we define a function which assigns a value of “Bit” and “Byte” to our firstName and lastName variables respectively.

What do you think?

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s