Curriculum
Course: AngularJS
Login

Curriculum

AngularJS

AngularJS Tutorial

0/65
Text lesson

Modules and Controllers in Files

In AngularJS applications, it’s common to place the module and controllers in separate JavaScript files. In this example, “myApp.js” includes the application module definition, whereas “myCtrl.js” contains the controller.

Example

<!DOCTYPE html>
<html>
<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js”></script>
<body>

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

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

</body>
</html>

myApp.js

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

The [] parameter in the module definition is used to specify dependent modules. If you omit the [] parameter, you are not creating a new module but instead retrieving an existing one.

myCtrl.js

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

Functions can Pollute the Global Namespace

Global functions should be avoided in JavaScript because they can be easily overwritten or removed by other scripts. AngularJS modules help mitigate this issue by keeping all functions confined to the module, ensuring they remain local.

When to Load the Library

Although it’s common practice in HTML applications to place scripts at the end of the <body> element, it is advisable to load the AngularJS library either in the <head> or at the beginning of the <body>. This is necessary because calls to angular.module can only be processed after the library has been loaded.

Example

<!DOCTYPE html>
<html>
<body>
<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js”></script>

<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>

</body>
</html>