Controller in AngularJs (Part 4)


Controller is the heart of angularJs. It provides the logic to control the view behavior. Controller is the mediator between model and view.

Controller should not reference or manipulate the DOM (Document Object Model) directly. Ng-controller directive is used to call the controller in angularJs.

Note: In the below code, I will show how to create controller and how to call controller in view file. For shake of simplicity I have kept all the logic in one html file. I hope you can easily separate the code into Model, View and Controller file.

Sample Code for Controller demo in AngularJs


<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
    <script src="../Scripts/angular.min.js"></script>
    
</head>
<body>
 <div ng-app="Myapp" ng-controller="myController">
    FirstName : <input type="text" ng-model="FirstName" > <br /> <br />
    LastName : <input type="text" ng-model="LastName" > <br /> <br />
    Complete Name : {{FirstName + " " + LastName }}
</div>
    <script>
       
   // You can keep this Code in separate model folder in JavaScript file
        var app = angular.module('Myapp', []);

   // You can keep this file under controller folder in JavaScript file.

        app.controller('myController', function ($scope) {
            $scope.FirstName = "Chandradev";
            $scope.LastName = "Sah";
        });
    </script>
</body>
</html>

Controller

Here model is the container for controller and $scope is the glue between controller and View. Controller always belongs to Module.

Other Ways to define the controller

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="../../../Angular Sample/Old Script/angular.js"></script>
    <script>
        var MyController = function ($scope) {
          $scope.Name = "Chandradev"
        }
    </script>
</head>
<body ng-app="">
    <div ng-controller="MyController">
       <b> {{Name}}</b>
    </div>
</body>
</html>

Summary:

In this article, we learnt the basic concept of controller in AngularJs.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.