Saturday, 22 December 2018

What is AngularJS Controllers


AngularJS Controllers

It is responsible to control the data or in other word, AngularJS controller is used to manage the flow of data of AngularJS application. ng-controller directive define the controller class to view. Attributes/properties and functions can be define in a controller. AngularJS invokes the controller with a $scope object.
AngularJS variable Example:-

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
    <div ng-app="myApp" ng-controller="TestController">
        Name: <input type="text" ng-model="name"><br>
        Address: <input type="text" ng-model="address"><br>
        <br>
        <p>Name: {{name}} </p>
        <p>Addess: {{address}} </p>
    </div>
    <script>
        var myapp = angular.module('myApp', []);
        myapp.controller('TestController', function ($scope) {
            $scope.name = "Alok";
            $scope.address = "Delhi";
        });
    </script>
</body>
</html> 

AngularJS variables as functions Example:-

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
    <div ng-app="myApp" ng-controller="TestController">
        First Name: <input type="text" ng-model="firstname"><br>
        Last Name:  <input type="text" ng-model="lastname"><br>
        Address:   <input type="text" ng-model="address">      
        <br>
        <p>Name: {{fullname()}} </p>
        <p>Addess: {{address}} </p>
    </div>
    <script>
        var myapp = angular.module('myApp', []);
        myapp.controller('TestController', function ($scope) {
            $scope.firstname = "Alok";
            $scope.address = "Delhi";
            $scope.lastname = "Singh"
            $scope.fullname = function () {
                return $scope.firstname + " " + $scope.lastname;
            };
        });
    </script>
</body>
</html> 
Remark:-
1:- Above code runs from root element define by “ng-app”
2:- ng-controller defines the controller object for an application.
3:- AngularJS will invoke the controller with a $scope object.
4:- we can define variable, function and assign it to scope that will invoke on view.
5:- You can use ng-model to perform two-way binding that reflect model if any changes occurs.

Use controllers to:
1:- Set up the initial state of the $scope object.
2:- Add behaviour to the $scope object.

Do not use controllers to:
1:- Format input
2:- Manipulate DOM
3:- Filter output
4:- Share code or state across controllers

No comments:

Post a Comment