An AngularJS controller is a JavaScript function that handles the logic for a specific part of an AngularJS application.
In AngularJS, a Controller gets the data from the View, processes it, and then delivers it to the view that is displayed to the end user. Your fundamental business logic will be stored in the Controller.
Role of an AngularJS Controller
Controllers are a core component in the Model-View-Controller (MVC) or Model-View-ViewModel (MVVM) patterns often associated with AngularJS. Their primary role is to bridge the gap between the application's model (data) and its view (HTML).
Key responsibilities include:
- Initializing Data: Setting up the initial state of data that will be displayed in the view.
- Processing Data: Handling user interactions (like button clicks or form submissions) and performing calculations or manipulations based on the data.
- Connecting to the Scope: Controllers interact with the
$scope
object, which acts as the glue between the controller and the view. Data attached to the$scope
within a controller becomes available in the view. - Storing Business Logic: As mentioned, fundamental business logic related to the view's behavior resides here.
How Controllers Connect to Views
Controllers are linked to a specific section of the HTML view using the ng-controller
directive. This directive specifies which controller JavaScript function should manage that part of the DOM.
<div ng-app="myApp" ng-controller="MyController">
<p>{{ greeting }}</p>
<button ng-click="changeGreeting()">Change Greeting</button>
</div>
angular.module('myApp', [])
.controller('MyController', function($scope) {
$scope.greeting = 'Hello, World!';
$scope.changeGreeting = function() {
$scope.greeting = 'Greetings from Controller!';
};
});
In this example:
MyController
is the JavaScript function.- It's associated with the
div
element usingng-controller="MyController"
. - Data (
greeting
) and functions (changeGreeting
) defined on$scope
in the controller are accessible within thatdiv
in the view.
Why Use Controllers?
- Separation of Concerns: They help separate the data and logic from the presentation (HTML).
- Maintainability: Centralizing logic makes the code easier to manage and update.
- Testability: Controllers can be tested independently of the view.
In essence, an AngularJS controller is the operational brain for a specific segment of your user interface, ensuring data flows correctly between your application's logic and what the user sees and interacts with.