Angularjs – Part Five

AngularJS Modules

Modules define your applications.

All your controllers should belong to a module.

Modules keep the global namespace clean.

In this example, “myApp.js” contains an application module definition, “myCtrl.js” contains a controller:


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


app.controller("myCtrl", function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";

Now index.html

<!DOCTYPE html>

<div ng-app=“myApp” ng-controller=“myCtrl”>
{{ firstName + ” ” + lastName }}

<script src=“//”></script>

<script src=“myApp.js”></script>
<script src=“myCtrl.js”></script>


Now if you run, you can see John Doe.


You can achieve the same by writing your js files in inline script like following..

<div ng-app=“myApp” ng-controller=“myCtrl”>
{{ firstName + ” ” + lastName }}

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

app.controller(“myCtrl”, function($scope) {
$scope.firstName = “John”;
$scope.lastName = “Doe”;

Controllers Pollute the Global Namespace

All examples, so far in this and prev tutorials, have used global functions.

Global variables and global functions should be avoided in all applications.

Global values (variables or functions) can be overwritten or destroyed by other scripts.

To solve this problem AngularJS uses modules.

Where to Put Module Definitions

A common advise for HTML applications, is to place all scripts at the very bottom of the <body> element.

This improves page loading, because HTML loading is not blocked by scripts loading.

In many AngularJS examples, you will se the Angular library being loaded in the <body> of the document.

In the example above, AngularJS is loaded in the <head> element, because the call to angular.module can only be done after the library has been loaded.

Another solution is to load the AngularJS library in the <body> element, but in front of your own AngularJS scripts:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s