Angularjs modules tutorial

AngularJS module:

An AngularJS module defines an application and used to separate logics like services, controllers and application etc. It acts as a container for the different parts of an application.

Note: To keep the code clean keep the modules in separate js files.

Angularjs creating modules:

We can create an angularjs module by using the AngularJS function angular.module.


<div ng-app="testApp">...</div>
var app = angular.module("testApp", []); 

Example Explanation:

In below example we have created two modules application and controller in testApp.js and appCtrl.js files. Remember a controller always belongs to a module, here controller defined in appCtrl.js file belongs to module defined in testApp.js file.

Note: Calls to angular.module can only be compiled after the AngularJS library has been loaded so it is recommended that we load the AngularJS library either in the head or at the start of the body tag.



var app = angular.module("testApp", []);

Note: Array [] parameter defines dependent modules. If we not pass this array parameter, new module will not be created and an existing one will retrieve.


app.controller("appCtrl", function($scope) {
    $scope.firstName = "Sunil";
    $scope.lastName= "Kumar";

Import above files in below file.

<!DOCTYPE html>
<div ng-app="testApp" ng-controller="appCtrl">
{{ firstName + " " + lastName }}
<script src="testApp.js"></script>
<script src="appCtrl.js"></script>

Try it:

JS Bin on

Please Share