AngularJS controllers control the data of AngularJS applications.
AngularJS controllers are regular JavaScript Objects.
AngularJS applications are controlled by controllers.
The ng-controller
directive is used to define the controller in the application. It connects the HTML view with the JavaScript logic.
A controller in AngularJS is simply a JavaScript object created using a standard JavaScript constructor function. It is responsible for setting up the data (model) and behavior (functions) that the view can use.
Application Explained
The AngularJS application is defined by the directive: ng-app="myApp"
. This tells AngularJS where the application starts. The app runs inside the specified HTML element (usually a <div>
).
The ng-controller="myCtrl"
directive defines an AngularJS controller named myCtrl
. It controls the data and logic for the application section.
The myCtrl
function is a regular JavaScript function. AngularJS automatically calls this controller and provides it with a special object called $scope
.
In AngularJS, the $scope
object acts as the "glue" between the controller and the view. It holds all the application variables and functions.
In this example, the controller creates two properties inside the scope: firstName
and lastName
. These properties store user data.
The ng-model
directive is used to bind the input fields to these scope properties. This enables two-way data binding — when the user types in the input field, the scope updates, and when the scope updates, the input reflects it automatically.
The example above demonstrated a controller object with two properties: lastName and firstName.
A controller can also have methods (variables as functions):
Controller Methods are functions defined inside controllers (e.g., $scope.fullName = function() {})
that perform actions or return computed values, like generating full names from inputs.
In larger AngularJS applications, it is common to store controllers in external files for better organization and maintainability.
Just copy the JavaScript code between the <script>
tags into a separate file named personController.js, and include it in your HTML using a script tag.
For the next example, we will create a new controller file:
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{ name: 'Jani', country: 'Norway' },
{ name: 'Hege', country: 'Sweden' },
{ name: 'Kai', country: 'Denmark' }
];
});
Save the file as namesController.js.
And then use the controller file in an application: