Angularjs Module & controller

M2-R5.1 · Chapter 6: JavaScript and Angular JS · 2 min read

Module & Controllers

Module 

  • A module is a container for different parts of an AngularJS application (controllers, services, directives, filters).

  • Syntax:

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

    • Organizes code into logical units.

    • Makes applications scalable and maintainable.

  • Notes:

  • The empty array [] defines dependencies (other modules).

  • Multiple controllers and services can belong to one module.

Controller

  • Definition: A controller is a JavaScript function that manages the data and logic of a view.

  • Syntax:

app.controller("myCtrl", function($scope) {

$scope.firstName = "Aditya";

$scope.lastName = "Pathak";

});
  • Role:

    • Connects the model ($scope) with the view (HTML).

    • Defines variables and functions accessible in the view.

  • Notes:

  • $scope is the glue between controller and view.

  • Multiple controllers can exist in one module, each handling a different part of the page.

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 = "Aditya";
  $scope.lastName = "Pathak";
});
</script>

</body>
</html>