Monday, May 12, 2014

AngularJS for Beginners: Scope, Controller

In AngularJS, a Controller is a JavaScript constructor function. This is used to add additional functionality to the scope of the view.

Scope
Now, what is Scope? Scope is an object that refers to the application model data. Scope is the object that works as the "Glue" between View and Controller. It holds the model data that is required to pass to the view. So, Scope is basically a kind of ViewModel.

When a new controller is created, AngularJS passes it a new child Scope object. This is available as a parameter ($scope) to the controller's constructor function.  AngularJS does this by using dependency injection here. A simple Controller function will look like the following:
    function MessageController($scope) {   
       $scope.textMsg = "Hello!";   
    }   
Controllers can be used in 2 ways: 1. Setting up the initial state of the $scope object. 2. Adding behavior to the $scope object.

Setting up the initial state of the $scope object
To set up initial state of a scope, we attach properties to the $scope object. The properties contain the view model. Let's use the same controller MessageController we have created in our previous example. Here we attach a property textMsg which contains a string value to the $scope:
    function MessageController($scope) {   
       $scope.textMsg = "Hello!";   
    }   
Each controller will be registered or attached to a template (view).  HTML elements (DOM) written with Angular-specific elements and attributes are called templates. All the $scope properties will be available to the template that the controller is registered. The 'ng-controller' directive is used to attach a controller to the view. See the following example:
      <div ng-controller=" MessageController ">  
            {{ textMsg }}  
      </div>  
In the above example, the controller MessageController is registered with the DOM element <div>. Therefore, the textMsg property is data-bound to the <div>.

In AngularJS, we can set any type including object on the $scope and show the object’s properties in the view. For example, let's create a person object with a single attribute name and set the $scope of our MessageController:
      function MessageController($scope) {  
           $scope.person = { name: "James" };  
      }  
We can access this person object in any child element of the <div> where the MessageController is registered. We can simply reference person.name in our view like the following:
      <div ng-controller=" MessageController ">  
            Hello {{ person.name }}  
      </div>  

Adding behavior to the $scope object
We have to add behavior to the scope in case of handling any event or executing any computation in the view. Behavior can be added to the scope by attaching functions to the $scope object. These functions then become available to be called from the template in which the controller is registered.  Here is an example of a controller that adds two methods to the scope:
      function CalulationController($scope) {  
           $scope.add = function(value) {   
                return value + 2;   
           };       
           $scope.subtract = function(value) {   
                return value - 2;   
           };       
      }  
If we attach the CalulationController to a <div>, the add and subtract methods can be invoked in the Angular expressions like the following:
      <div ng-controller=" CalulationController">  
            5 plus 2 is equal to {{ add(5) }}  
           <br>  
            5 minus 2 is equal to {{ subtract(5) }}            
      </div>  

ng-click
In order to specify custom behavior when a DOM element (button, link etc.) is clicked, the ng-click directive is used. The ng-click directive can bind the click event of the DOM element with any function specified in the $scope. Look at the following controller example:
      function CalulationController($scope) {  
           $scope.result = 0;  
           $scope.add = function(value) {   
                $scope.result += value;   
           };  
           $scope.subtract = function(value) {   
                $scope.result -= value;   
           };       
      }       
Let's attach the CalulationController to a <div> which contains two buttons. The click event of the buttons can be bound the scope functions add and subtract like the following:
      <div ng-controller="CalulationController">  
           <button ng-click="add(5)">Add 5</button>  
           {{ result }}  
           <br>  
           <button ng-click="subtract(5)">Subtract 5</button>  
           {{ result }}  
      </div>  

A small example
Here is a small example with the things we have learnt in this post:
 <!DOCTYPE html>  
 <html ng-app>  
 <head>  
    <title>Learning AngularJS</title>  
    <script src="angular.min.js"></script>  
 </head>  
 <body>  
      <div ng-controller="BooksController">  
           <br>  
           List of books:  
           <br>                  
           <ul>  
                <li ng-repeat="book in bookList">  
                     {{book.name}} -- {{book.author | uppercase}}   
                </li>  
           </ul>  
           Book name: <input type="text" ng-model="bookName" />  
           Author: <input type="text" ng-model="bookAuthor" /> <br>  
           <button ng-click="add()">Add</button>  
      </div>
  
      <script>             
           function BooksController($scope) {  
                $scope.bookList = [  
                     {name:'The Tempest',   
                          author:'William Shakespeare'},  
                     {name:'Gitanjali',   
                          author:'Rabindranath Tagore'},  
                     {name:'Harry Potter',   
                          author:'J. K. Rowling'},  
                     {name:'The Da Vinci Code',   
                          author:'Dan Brown'},  
                     {name:'A Brief History of Time',   
                          author:'Stephen Hawking'},  
                     {name:'Tell Me Your Dreams',   
                          author:'Sidney Sheldon'}  
                ]; 
 
                $scope.add = function() {  
                     $scope.bookList.push({   
                          name: $scope.bookName,   
                          author: $scope.bookAuthor   
                     });  
                };  
           }                      
       </script>  
 </body>  
 </html>  

We should see something like the following in the browser:





If a new book name and author name is entered and Add button is clicked, the entry will be added in the list.

[TOC]    << Previous    Next >>

1 comment:

  1. There are a couple of solutions to this: the so-called Controller As syntax introduced by AngularJS 1.2 and .component() method introduced by AngularJS 1.5. The latter option is a recommended way to go if you are thinking about upgrading your application to newer Angular versions. In this post we’ll talk about AngularJS Controller As syntax.
    AngularJS Training and Tutorial
    AngularJS Training in chennai
    AngularJS Training and placement in chennai

    ReplyDelete