The Angularjs module defines a application.
A module is a container for different parts of a application.
All controllers in the application should belong to a module.
Module with one controller
The following application ("MyApp") contains a controller ("Myctrl"):
<!DOCTYPE HTML><HTML><Scriptsrc= "Http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></Script><Body><DivNg-app= "MYAPP"Ng-controller= "Myctrl">{{firstName + "" + LastName}}</Div><Script>varapp=Angular.module ("myApp", []); App.controller ("Myctrl", function($scope) {$scope. FirstName= "John"; $scope. LastName= "Doe";});</Script></Body></HTML>
Run
Defining modules and controllers in JS files
In ANGULARJS applications, we typically define modules and controllers in different JavaScript files.
In the following example, "Myapp.js" contains a application module definition, "myctrl.js" contains the definition of the controller:
<!DOCTYPE HTML><HTML><Scriptsrc= "Http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></Script><Body><DivNg-app= "MYAPP"Ng-controller= "Myctrl">{{firstName + "" + LastName}}</Div><Scriptsrc= "Myapp.js"></Script><Scriptsrc= "Myctrl.js"></Script></Body></HTML>
Myapp.js Code:
var app = Angular.module ("myApp", []);
|
The parameter [] here can be used to specify the module's dependencies (that is, other modules that need to be loaded) |
Myctrl.js Code:
function ($scope) { $scope. firstName = "John"; $scope. LastName= "Doe";});
function pollution in Global namespace
Try to avoid using global functions in JavaScript. Because global functions are easily overwritten or destroyed by other JavaScript code.
The definition of the ANGULARJS module reduces the risk of this problem and, as far as possible, defines the function in the Angularjs module.
When will the library be loaded?
|
In all of our sample code, the AngularJS library is loaded in the head section of the HTML document. |
It is recommended that you place a reference to the script at the end of the <body> element. But you'll still see a lot of angularjs. The sample code places the library reference in the head part of the document just to compile the access to the Angular.module after the library is loaded.
Another workaround is to place a reference to the ANGULARJS library before your own Angularjs script code at the end of the <body> element:
<!DOCTYPE HTML><HTML><Body><DivNg-app= "MYAPP"Ng-controller= "Myctrl">{{firstName + "" + LastName}}</Div><Scriptsrc= "Http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></Script><Script>varapp=Angular.module ("myApp", []); App.controller ("Myctrl", function($scope) {$scope. FirstName= "John"; $scope. LastName= "Doe";});</Script></Body></HTML>
Previous chapter-Angularjs Quick Start Guide 11: Events Next chapter-Angularjs Quick Start Guide 13: Forms
ANGULARJS Quick Start Guide 12: Modules