Step 5-AngularJS Controller

Definition – AngularJS controller is a java-script object which controls the data.

Syntax-  ng-controller

The AngularJS controller consists of the following components:

  1. Data: The AngularJS controller contains the data of the application, which is used to display the content on the view.
  2. Scope: The AngularJS controller is associated with the $scope object, which is used to share data between the view and the controller.
  3. Business Logic: The AngularJS controller contains the business logic of the application. It is used to manipulate the data and perform various operations.
  4. Events: The AngularJS controller is used to handle the events of the application. It is used to trigger the events and respond to them.

Advantages of AngularJS Controller:

  1. Separation of Concerns: The AngularJS controller follows the Model-View-Controller (MVC) architecture, which separates the concerns of the application. It separates the business logic from the presentation logic.
  2. Reusability: The AngularJS controller can be reused in multiple views. It reduces the code duplication and improves the maintainability of the application.
  3. Testability: The AngularJS controller is easy to test, as it contains the business logic of the application. It can be tested in isolation, without any dependency on the view or the model.

Now look on below code example- You can save it as html file and open on browser

<!DOCTYPE html>
<html ng-app="myApp">
	<title>AngularJS Controller Example</title>
	<script src=""></script>
		// Define the AngularJS module
		var app = angular.module("myApp", []);
		// Define the AngularJS controller
		app.controller("myCtrl", function($scope) {
			// Define the data of the application
			$scope.firstName = "John";
			$scope.lastName = "Doe";
			$scope.fullName = function() {
				return $scope.firstName + " " + $scope.lastName;
			// Define the business logic of the application
			$scope.reverseName = function() {
				$scope.firstName = $scope.firstName.split('').reverse().join('');
				$scope.lastName = $scope.lastName.split('').reverse().join('');
<body ng-controller="myCtrl">
	<h1>AngularJS Controller Example</h1>
	<!-- Display the data using the scope variables -->
	<p>First Name: {{firstName}}</p>
	<p>Last Name: {{lastName}}</p>
	<p>Full Name: {{fullName()}}</p>
	<!-- Trigger the business logic using ng-click directive -->
	<button ng-click="reverseName()">Reverse Name</button>


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.