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:

myApp.js:

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

myCtrl.js:

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

Now index.html

<!DOCTYPE html>
<html>
<body>

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

<script src=“//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js”></script>

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

</body>
</html>

Now if you run, you can see John Doe.

Eg: http://www.w3schools.com/angular/tryit.asp?filename=try_ng_module_files

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

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

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

app.controller(“myCtrl”, function($scope) {
$scope.firstName = “John”;
$scope.lastName = “Doe”;
});
</script>

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:

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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