×

Html & Html5

The World's best Software Development Study Portal

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 controllers control the data of AngularJS applications.

  • AngularJS controllers are regular JavaScript Objects.



  • Examples:

    	<div ng-app="myApp"  ng-controller="myCtrl" >
    
          First Name: <input type="text" ng-model="firstName">
          Last Name: <input type="text" ng-model="lastName">
    
    Full Name: {{firstName + " " + lastName}} </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.firstName = "John"; $scope.lastName = "Doe"; }); </script>

    Output

    First Name:

    Last Name:

    Full Name: {{firstName + " " + lastName}}




        <div ng-app="myApp" ng-controller="personCtrl">
    First Name: <input type="text" ng-model="firstName"><br> Last Name: <input type="text" ng-model="lastName"><br> <br> Full Name: {{fullName()}} </div>
    <script> var app = angular.module('myApp', []); app.controller('personCtrl',function($scope) {   $scope.firstName = "Marky";   $scope.lastName = "Steven";   $scope.fullName = function() {     return $scope.firstName + " " + $scope.lastName;   }; }); </script>

    Controller Methods

    The example above demonstrated a controller object with two properties: lastName and firstName.

    A controller can also have methods variables as functions.
    The ng-controller="myCtrl" attribute defines a controller.

    The myCtrl function is a JavaScript function.

    AngularJS will invoke the controller with a $scope object.

    A controller can also have methods.


    Controllers In External Files

    In larger applications, it is common to store controllers in external files like.

    <script src="personController.js"></script>



    Keypoints


    1)AngularJS controllers are used to control the flow of data of AngularJS application.

    2) A controller is defined using ng-controller directive.

    3) A controller is a JavaScript object containing attributes/properties and functions.

    4) Each controller accepts $scope as a parameter which refers to the application/module that controller is to control.

    5) AngularJS controllers control the data of AngularJS applications.

    6) AngularJS controllers are regular JavaScript Objects.


    Why we use ng controller in AngularJS?


    The ng-controller Directive in AngularJS is used to add controller to the application. It can be used to add methods, functions and variables that can be called on some event like click, etc to perform certain action. Where expression refers to the name of the controller.