AngularJS Controllers
AngularJS controllers are JavaScript functions that supply data and behavior to a view through the $scope object.
What Is a Controller?
A controller in AngularJS is a plain JavaScript constructor function that AngularJS invokes with the $scope object injected in. The controller's job is to set up the initial state of $scope and add behavior to it, such as methods that respond to user actions.
Controllers are attached to a section of HTML using the ng-controller directive. Everything inside that HTML element can access properties defined on $scope inside the controller.
Defining a Controller
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<script>
var app = angular.module("myApp", []);
app.controller("personCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>Using ng-controller
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="personCtrl">
First Name: {{ firstName }}<br>
Last Name: {{ lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("personCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>Adding Methods to the Scope
Besides plain data, a controller can attach functions to $scope. These functions can then be called directly from the view, for example from an ng-click handler.
A Controller Method
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<script>
var app = angular.module("myApp", []);
app.controller("personCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>
</body>
</html>- Controllers should contain view logic only, not business logic — heavier tasks belong in services.
- Each ng-controller creates its own child scope, isolated from other controllers on the page.
- A controller function name is conventionally suffixed with Ctrl or Controller for clarity.
Controllers in External Files
As an application grows, controllers are usually moved out of inline scripts and into their own .js files, still registered on the same module object so they share module-level dependencies.
External Controller File
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<script>
var app = angular.module("myApp", []);
</script>
<script>
// personController.js
angular.module("myApp").controller("personCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>Exercise: AngularJS Controllers
What is the purpose of the ng-controller directive?