Open In App

AngularJS $controller Service

Last Updated : 02 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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=
    </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=
    </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=
    </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.

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads