Angular.js Modules

Angular.js is an open source web framework. It is widely used for facing the challenges encountered in the development of single page applications. In Angular.js Modules plays an important role since Angular.js apps are modular. Angular has its own modularity system. It is called NgModules. Modules are containers for different parts of the applications and it defines an application. Module is also a container for application controllers. Modules are created by using angular.module function. An example is given below.


<div ng-app="myApp">...</div>

<script>

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

</script>


 In this example myApp is a parameter that refers to an HTML element in which the application runs. To separate logics like services, controllers, applications etc from the code  modules are used. Lets see another example. We have two modules in this example, application module which we will use to initialize application with controllers, another one is controller module which is used to define controllers.

mainApp is our application, we define it using angular.module function and pass an empty array.


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


In our studentController.js controller module we declare the studentController module with mainApp.controller function as given below.


mainApp.controller("studentController", function($scope) {

   $scope.student = {

      firstName: "Mahesh",

      lastName: "Parashar",

      fees:500,

      

      subjects:[

         {name:'Physics',marks:70},

         {name:'Chemistry',marks:80},

         {name:'Math',marks:65},

         {name:'English',marks:75},

         {name:'Hindi',marks:67}

      ],

      fullName: function() {

         var studentObject;

         studentObject = $scope.student;

         return studentObject.firstName + " " + studentObject.lastName;

      }

   };

});


For the application module we use ng-app directive and for controllers we use ngcontroller directive and import two of the js files, mainApp.js and studentController.js in our main HTML page as shown below.


<div ng-app = "mainApp" ng-controller = "studentController">

   ...

   <script src = "mainApp.js"></script>

   <script src = "studentController.js"></script>

</div>