AngularJS Controllers

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

AngularJS Controllers

AngularJS controllers are used to control the flow of data of AngularJS application. A controller is defined using ng-controller directive. A controller is a JavaScript object containing attributes/properties and functions. Each controller accepts $scope as a parameter which refers to the application/module that controller is to control.


AngularJS Controller Example

  

  

  1.   
  2.  
  3.   
  4.  
  5.   
  6.   
  7.   
  8. First Name: 
      
  9. Last Name: 
      

  10.   
  11. Full Name: {{firstName + " " + lastName}}  
  12.   
  13.   
  14.   
  15.   
  16.   
  17.   
  18.   

Test it Now

Note:

  • Here, the AngularJS application runs inside the
    is defined by ng-app="myApp".
  • The AngularJS directive is ng-controller="myCtrl" attribute.
  • The myCtrl function is a JavaScript function.
  • AngularJS will invoke the controller with a $scope object.
  • In AngularJS, $scope is the application object (the owner of application variables and functions).
  • The controller creates two properties (variables) in the scope (firstName and lastName).
  • The ng-model directives bind the input fields to the controller properties (firstName and lastName).

AngularJS controller example with methods (variables as functions)

  

  

  1.   
  2.  
  3.   
  4.  
  5.   
  6.   
  7.   
  8. First Name: 
      
  9. Last Name: 
      

  10.   
  11. Full Name: {{fullName()}}  
  12.   
  13.   
  14.   
  15.   
  16.   
  17.   

Test it Now


AngularJS Controller in external files

In larger applications, generally the controllers are stored in external files.

Create an external file named "personController.js" to store controller.

Here, "personController.js" is:

  1.    angular.module('myApp', []).controller('personCtrl', function($scope) {  
  2.     $scope.firstName = "Aryan",  
  3.     $scope.lastName = "Khanna",  
  4.     $scope.fullName = function() {  
  5.         return $scope.firstName + " " + $scope.lastName;  
  6.     }  
  7. });  

See this example:

    

  1.   
  2.  
  3.   
  4.  
  5.   
  6. First Name: 
      
  7. Last Name: 
      

  8.   
  9. Full Name: {{firstName + " " + lastName}}  
  10.   
  11.   
  12.   
  13.