AngularJS $controller Service
Last Updated :
02 Jan, 2023
AngularJS applications depend on a controller to control the flow of data through an AngularJS application. AngularJS architecture uses the MVC model i.e the Model View Controller. The model is responsible for maintaining the application data, the View for displaying data or some part of data to the user, and the controller for communication between the model and the view. A Controller is a JavaScript object that consists of various attributes, properties, and functions. Properties can be added to the controller using the $scope object. The $scope object acts as a glue between the controller and view. It simply acts as the glue between the model and the view. They take input from the view, process it, and return the output to be displayed to the user.
The $controller service is used to instantiate a controller. It is a call to the $injector but extracted into a service.
Syntax:
$controller(constructor, locals);
Parameter Values: The $controller takes 2 arguments:
- constructor: If the constructor is called with a function then it is regarded as a controller constructor function else it is considered to be a string, that can be utilized to retrieve the controller constructor with the following steps:
- By checking the controller with the mentioned name that will be registered via $controllerProvider.
- By evaluating the string with the current scope that will return a constructor.
- locals: It is of an object type with injecting the locals for the Controllers.
Return Type: It returns an object that is an instance for the given controller.
Approach: The $controller can be implemented with the following approach:
- Specify the controller's name in the ng-controller directive inside an HTML element where you want to use the properties of the controller.
<div ng-app = "myApp" ng-controller = "myCtrl">
- Inside the script tag, create a module.
var app = angular.module
- Using the module, create a controller using the JavaScript object constructor and pass scope as an argument.
app.controller("myCtrl",function($scope)){}
- Attach properties to the controller using the scope object.
Example 1: This example shows how to create a controller and use its properties in an HTML element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>$controller Service in AngularJS</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body ng-app="myApp">
<h1>
Creating a controller and using its properties in a tag.
</h1>
<div ng-controller="myCtrl">
<h1>{{title.title1}}</h1>
<h2>{{title.title2}}</h2>
<ul ng-repeat="x in topics">
<li>{{x}}</li>
</ul>
</div>
<script type="text/javascript">
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.title = {
"title1": "GeeksforGeeks",
"title2": "AngularJS Controller"
}
$scope.topics =
["Expressions",
"Controller",
"Routing",
"Services"];
});
</script>
</body>
</html>
Explanation: In the above example, we have created a module named "myApp". We have attached a controller named "myCtrl" to the module using the JavaScript constructor and have passed $scope as a parameter. We have attached properties like string, object, and array to the controller using the $scope object. We have used these properties in the <div> tag where we have specified the controller using the ng-controller directive.
Output:
Example 2: In this example, we will be creating an external file for the controller.
In larger applications, controllers are stored in external files. To implement this, from the above example you just need to put the code inside the <script> tag where the module and controller are being created in a separate file and save this file with the .js extension. Link this file in the src attribute of the <script> tag.
index.html:
HTML
<!DOCTYPE html>
<html>
<head>
<title>
$controller Service in AngularJS
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body ng-app="myApp">
<h1>
Creating a separate file for the controller.
</h1>
<div ng-controller="myCtrl">
<h1>{{title.title1}}</h1>
<h2>{{title.title2}}</h2>
<ul ng-repeat="x in steps">
<li>{{x}}</li>
</ul>
</div>
<script src="app.js"></script>
</body>
</html>
app.js
var app=angular.module("myApp",[]);
app.controller("myCtrl",function($scope){
$scope.title={
"title1":"GeeksforGeeks",
"title2":"AngularJS Controller"
}
$scope.steps=
["Create a file with .js extension",
"In this file write the JavaScript code of
creating the module and controller",
"Link this file in the main HTML file by
using src attribute of the <script> tag"];
});
Explanation: In the above example we have made a separate .js file to write the code for the controller. In the index.html we have created the AngularJS app and imported the app.js file to use the properties of the controllers.
Output:
Example 3: In this example, we will be performing the basic arithmetic operations on 2 numbers entered by the user.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
$controller Service in AngularJS
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body ng-app="myApp">
<h2>GeeksforGeeks</h2>
<h4>
AngularJS $Controller Service
</h4>
<div ng-controller="myCtrl">
<form>
<label>Enter first number:</label>
<input type="number"
name="num1"
ng-model="num1">
<br>
<label>Enter second number:</label>
<input type="number"
name="num2"
ng-model="num2">
<br>
<br>
<input type="button"
name="add"
value="Add"
ng-click="add()">
<input type="button"
name="subtract"
value="Subtract"
ng-click="subtract()">
<input type="button"
name="multiply"
value="Multiply"
ng-click="multiply()">
<input type="button"
name="divide"
value="Divide"
ng-click="divide()">
</form>
<p ng-show="answer!='nil'">
Answer : {{answer}}
</p>
</div>
<script type="text/javascript">
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.answer = "nil";
$scope.add = function() {
$scope.answer = $scope.num1 + $scope.num2;
}
$scope.subtract = function() {
$scope.answer = $scope.num1 - $scope.num2;
}
$scope.divide = function() {
$scope.answer = $scope.num1 / $scope.num2;
}
$scope.multiply = function() {
$scope.answer = $scope.num1 * $scope.num2;
}
});
</script>
</body>
</html>
Explanation: In the above example, we created different functions for different operations inside the controller. When a button is clicked the function specified in the ng-click directive is called and the answer is calculated and displayed.
Output: When the user enters two numbers and clicks on Add button the two numbers are added and the output is shown. Similarly, the output will be shown when the buttons Subtract, Multiply and Divide are clicked.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read