Click here to Skip to main content
15,881,812 members
Articles / Web Development / HTML

Understanding AngularJS

Rate me:
Please Sign up or sign in to vote.
4.70/5 (28 votes)
24 Sep 2013CC (ASA 3U)4 min read 81.4K   61   12
Understanding AngularJS

Introduction

In the world of web application development, currently one of the most talked about capabilities is to have dynamic web pages. That is, binding data to page and collecting data from the page should be quick and also easy. And we are very fortunate to have JavaScript frameworks like Backbone (from individual contributor), Knockout (from Microsoft), AngularJS (from Google), etc. These frameworks embrace the strengths of HTML and CSS and provide MVC design approach at the client side.

AngularJS

I am assuming the reader has a fair understanding of the MVC design approach, the associated different components and the benefits of using it. AngularJS embraces the benefits of MVC and provides an easy and rich way of binding data (model) to the HTML (view) through controller. With little effort, one may make the HTML very dynamic and responsive to the underlying model. So if the model is changed, it gets quickly reflected in the view and when any changes are made in the view, the model is changed accordingly. And this could be done without using the complicated HTML DOM operations.

AngularJS Blocks

  1. Model: The data or the state represented by the web application or to be specific, the state of the concerned web page.
  2. View: The visual representation and projection of model. Its responsibility is to present the information in model in a user appreciable format.
  3. Controller: The brain dictating the application behavior. Its responsibility is to link the right model with the right view.

Steps to Leverage AngularJS

  1. Include the AngularJS framework - Embed the following script tag in the HTML page:
    HTML
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script> 

    Refer to the site- http://angularjs.org/ to understand the latest version or it could even be downloaded from there and referred locally in the web page.

  2. Define root scope - Tell the AngularJS from where the elements are to be considered under the scope of the framework:

    For example to the form, body or any element which is going to hold the HTML template for the AngularJS, add the attribute- ng-app:

    HTML
    <form id="mainform" ng-app>
    ...
    </form>
  3. Bind model to view - This is one of the important steps which binds the different HTML elements to the model or to be specific model property:

    For example, consider a model- Employee with properties like Last Name, First Name, Id, etc. The binding is done using the attribute- ng-model:

    HTML
    <table>
    <tr>
    <td>
    Last Name
    <input type="text" id="txtLastName" ng-model="Employee.LastName" />
    </td>
    </tr>
    <tr>
    <td>
    First Name
    <input type="text" id="txtFirstName" ng-model="Employee.FirstName" />
    </td>
    </tr>
    <tr>
    <td>
    Id
    <input type="text" id="txtId" ng-model="Employee.Id" />
    </td>
    </tr>
    <tr>
    <td>
    Current City
    <input type="text" id="txtCurrentCity" ng-model="Employee.CurrentCity" />
    </td>
    </tr>
    <tr>
    <td>
    Current State
    <input type="text" id="txtCurrentState" ng-model="Employee.CurrentState" />
    </td>
    </tr>
    <tr>
    <td>
    Current Country
    <input type="text" id="txtCurrentCountry" ng-model="Employee.CurrentCountry" />
    </td>
    </tr> 
    </table> 

    So the moment any change is done to any of the input text boxes, the corresponding property of the bound model- Employee, will get updated automatically without a single line of extra code. And then one may easily extract the data entered in the UI using a special object- $scope introduced by AngularJS. We will see how once we discuss the controller.

    This binding could also be leveraged to sync with the different views and elements using the model properties as:

    HTML
    <table width="100%">
    <tr>
    <td>
    {{ Employee.LastName }}
    </td>
    </tr>
    <tr>
    <td>
    {{ Employee.FirstName }}
    </td>
    </tr>
    <tr>
    <td>
    {{ Employee.Id }}
    </td>
    </tr>
    <tr>
    <td>
    {{ Employee.CurrentCity }}
    </td>
    </tr>
    <tr>
    <td>
    {{ Employee.CurrentState }}
    </td>
    </tr>
    <tr>
    <td>
    {{ Employee.CurrentCountry }}
    </td>
    </tr> 
    </table> 

    The double curly brace notation- {{ Employee.LastName }} is a way to bind data for viewing. The expression between the curly braces is evaluated the moment the corresponding property of the model is changed. In traditional approach, to achieve such synchronization using JavaScript we had to deal with lots of DOM operations to read from and then to assign to HTML elements.

  4. Define Controller - Controller as explained earlier does the real job of linking the model to the view. The different operations that one may achieve in controller are for example, instantiating the model from the available data (e.g. data probably fetched from the service call, etc.), defining behavior like collecting data from the UI elements and then post to some service on some event like button click, etc.

    The controller is defined using the attribute- ng-controller:

    HTML
    <form id="mainform" ng-controller="EmpController" ng-app>
    ...
    </form> 

    Once the controller is defined, instantiate model using jquery as:

    JavaScript
    function EmpController ($scope) {
    $scope.Employee= { LastName: 'Bandopadhyaya', 
    FirstName:’Rahul’,
    …
    CurrentCountry:’India’};
    } 

    Where “EmpController” is the controller defined. And $scope is a AngularJS provided object which bridges the controller and the view.

    Similarly, using $scope, one may extract data in the controller from the UI (and hence the model) and then post it to some service as:

    JavaScript
    function EmpController ($scope) {
    $scope.Employee= { LastName: 'Bandopadhyaya', 
    FirstName:’Rahul’,
    …
    CurrentCountry:’India’};
    
    ...
    $scope.save = function () {
    var emp = new Employee2();
    emp.LastName = $scope.Employee.LastName;
    emp.FirstName = $scope.Employee.FirstName;
    emp.Id = $scope.Employee.Id;
    emp.CurrentCity = $scope.Employee.CurrentCity;
    emp.CurrentState = $scope.Employee.CurrentState;
    emp.CurrentCountry = $scope.Employee.CurrentCountry;
    $.ajax({
    type: "POST",
    url: "service url",
    data: JSON.stringify(emp),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
    alert("Employee Added");
    },
    error: function (msg) {
    alert("Error while adding employee, please try again...");
    }
    });
    };
    
    } 

    Where Employee2 is some local JavaScript class:

    JavaScript
    function Employee() {
    this.LastName ="";
    this.FirstName ="";
    this.Id = 0;
    this.CurrentCity ="";
    this.CurrentState ="";
    this.CurrentCountry ="";
    } 

    And “$scope.save” is an interface which may be called for example on a button click as:

    HTML
    <input type="button" id="btnAddEmp" value="
    Add Employee" ng-click="save()" />

Conclusion

So, the intention of this article is to articulate how using frameworks like AngularJS, one may create dynamic web pages with some basic behaviors quickly and that too without needing complicated scripting knowledge. We have also understood the different steps (but not limited to) that are required to leverage the capability of AngularJS.

Reference

Appendix

While accessing the web application having AngularJS in Internet Explorer, make sure to keep the browser mode to IE9 (refer to the Developer Tools- F12), otherwise the application may not behave as intended.

License

This article, along with any associated source code and files, is licensed under The Creative Commons Attribution-Share Alike 3.0 Unported License


Written By
Architect Infosys Limited
India India
I am currently working as Technical Architect in Infosys Limited and My motto is "share the good knowledge so that my fellow colleague or those from the same profession may not face the same issue as I have had… enjoy coding and sharing knowledge"

"Disclaimer: Any views or opinions presented in this article are solely those of the author and do not represent those of Infosys Limited. Infosys Limited does not accept any liability in respect of any views or content present herein."

Comments and Discussions

 
GeneralGood work Pin
Sachin Makwana3-Jan-16 22:39
professionalSachin Makwana3-Jan-16 22:39 
GeneralMy vote of 3 Pin
Member 948830718-Aug-14 6:08
Member 948830718-Aug-14 6:08 
GeneralMy vote of 4 Pin
Member 68981313-Jun-14 18:04
Member 68981313-Jun-14 18:04 
QuestionOne query Pin
Tridip Bhattacharjee21-Feb-14 3:45
professionalTridip Bhattacharjee21-Feb-14 3:45 
AnswerRe: One query Pin
Debabrata_Das13-Jul-14 7:32
professionalDebabrata_Das13-Jul-14 7:32 
QuestionBINDING PROBLEM IN ANGULAR JS Pin
Dharmit vyas20-Feb-14 21:35
Dharmit vyas20-Feb-14 21:35 
AnswerRe: BINDING PROBLEM IN ANGULAR JS Pin
papab3014-Mar-14 6:29
papab3014-Mar-14 6:29 
AnswerRe: BINDING PROBLEM IN ANGULAR JS Pin
vinodkumarnie24-Feb-16 18:04
vinodkumarnie24-Feb-16 18:04 
GeneralMy Vote of 4 Pin
SankarHarsha27-Sep-13 2:26
SankarHarsha27-Sep-13 2:26 
GeneralMy vote of 3 Pin
jphamilton25-Sep-13 3:23
jphamilton25-Sep-13 3:23 
GeneralMy vote of 5 Pin
Nitin Singh India24-Sep-13 6:58
Nitin Singh India24-Sep-13 6:58 
Questionvery simple description Pin
Nitin Singh India24-Sep-13 6:57
Nitin Singh India24-Sep-13 6:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.