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.
Syntax:
<div ng-app="testApp">...</div> <script> var app = angular.module("testApp", []); </script> |
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.
Example:
testApp.js
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.
appCtrl.js
app.controller("appCtrl", function($scope) { $scope.firstName = "Sunil"; $scope.lastName= "Kumar"; }); |
Import above files in below file.
<!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"> </script> </head> <body> <div ng-app="testApp" ng-controller="appCtrl"> {{ firstName + " " + lastName }} </div> <script src="testApp.js"></script> <script src="appCtrl.js"></script> </body> </html> |