AngularJs Tutorial Modules And Controllers

Modules And Controllers are very important topics in angularjs module and controller is heart of angularjs.

In this Tutorial we will learn following points :

    What is a module and how to create module in angular js.
    What is a controller and how to create controller in angular js.
    How to register a controller with the module.
    How to use the module that we created to bootstrap the angular application.

What is a module in angularjs?

A module is a container for a different parts of your application i.e controllers, services, directives, filters, etc.
You can think of module as a Main() method in other types of application.

Now we will create one module :
Use the angular object’s module() method to create module.

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

In the above script inside module method first occurrence is Name of the module and second for add Dependency of other module.

What is a controller in angularjs?

A controller is a javascript function in angular js.
The job of the controller is to build a model for the view to display.

How to create controller in angularjs :

In the below script you can see two way to register controller with the module.you can create folder inside your project and type below code in your script.js file.

//module
var myApp = angular.module("myModule", []);
var myController = function($scope) {
	$scope.message = "AngularJs Tutorial";
}
//controller register with module
myApp.controller ("myController",myController);

OR

//module
var myApp = angular.module("myModule", []);
//controller register with module
myApp.controller ("myController", function($scope) {
	$scope.message = "AngularJs Tutorial";
}

craete one html file and include script.js file.

<html ng-app="myModule">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<script src="script/script.js"></script>
</head>
<body>
	<div ng-controller="myController">
		{{message}}
	</div> 
	
</body>
</html>

Output will be :

AngularJs Tutorial