What are the controllers in AngularJS?

Controllers are JavaScript functions which are used to provide data and logic to HTML UI. It acts as an interface between Server and HTML UI. Each controller accepts $scope as a parameter which refers to the application/module that controller is going to control. For example:

var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope) {
$scope.firstName = “Aryan”;
$scope.lastName = “Khanna”;
});

In AngularJS, controllers are JavaScript functions that are used to manage the data and behavior of a specific part of the application. They act as the bridge between the data model and the view, handling user input and updating the model accordingly.

In the context of AngularJS, controllers are defined using the controller function. The controller function takes two parameters: the controller name and a function that contains the logic for the controller.

Here’s a basic example of an AngularJS controller:

javascript
var myApp = angular.module(‘myApp’, []);

myApp.controller(‘MyController’, function($scope) {
// Controller logic goes here
$scope.message = ‘Hello, AngularJS!’;
});

In this example, the MyController controller is defined within the myApp module. The controller function takes $scope as a parameter, which is an object that acts as a glue between the controller and the view. The message variable is then assigned to the $scope object, making it accessible in the associated view.

In the HTML, you would reference this controller using the ng-controller directive:

html
<div ng-app=”myApp” ng-controller=”MyController”>
{{ message }}
</div>

This is a basic overview of controllers in AngularJS. They play a crucial role in organizing and managing the application’s logic and data. Keep in mind that AngularJS is an older version of Angular, and newer versions of Angular use a different approach with components.