AngularJS Controller

Introduction

AngularJS Controllers follows MVC ( Model-View-Controller ) pattern. In the MVC pattern in AngularJS, a Controller controls the interaction between the View and Model. View handles the layout while the Model handles business logic.

A Controller is defined using ng-controller in an AngularJS application. AgnularJS applications depend on Controller which controls the flow of data. Each Controller accepts $Scope as a parameter which refers to the application or module that the Controller is needed to control.

CSS

  1. <style>  
  2.         .input { border-radius: 5px; text-align: center; padding-left: 10px;  
  3.             border: 1px solid gray; margin: 5px; background-color: lightgray;  
  4.             width: 200px;  
  5.         }  
  6.     </style>  
JS
  1. <script>    
  2.         var app = angular.module("App", [])    
  3.         app.controller("AjController", function ($scope) {    
  4.             $scope.message = "Please enter your name and age";    
  5.             $scope.person = {    
  6.                 Name: null,    
  7.                 Age: null,    
  8.           Show: function () {    
  9.                         var personObj = $scope.person;    
  10.                         $scope.NameAndAge = "Hello, " + personObj.Name + " you are "                                                      + personObj.Age + " year old.";    
  11.                         $scope.disabled = true;    
  12.                 }    
  13.             };    
  14.         });    
  15.     </script>    
HTML
  1. <body ng-app="App" style="padding:15% 10% 15% 40%">  
  2.     <div style="text-align:center; border:solid 2px gray;width:50%">  
  3.         <h2 style="text-decoration: underline;color:dodgerblue">AngularJs - Controllers</h2>  
  4.         <div ng-controller="AjController"> <span>{{message}}</span>  
  5.             <hr /> <input type="text" ng-disabled={{ "disabled"}} ng-model="person.Name" class="input" placeholder="Enter your Name" /> <br /> <input type="text" ng-disabled={{ "disabled"}} ng-model="person.Age" class="input" placeholder="Enter your Age" /> <br /> <button ng-model="all" ng-click="person.Show()"> Show</button>  
  6.             <hr /> <span ng-show="person.Name===''||person.Age===''?false:true">{{NameAndAge}}    
  7. </span> </div>  
  8.         <div>  
  9. </body>    
AjController is an Angular controller defined with $scope as argument. $scope refers to the application which is using the AjController. $scope.person is the property of AjController. Name, Age, and Show is the property of $scope.person object.
 
Figure 1.1 

Put your name and age and click the "Show" button. 
 
Figure 1.2

Summary

In this blog, I discussed how we can use ternary operator using AngularJS and in which directives of AngularJS we can use them.