Pages

Wednesday 21 October 2015

How to create angularJs Application in eclipse

          In this tutorial we are going to create simple AngularJs application with very basics features. As you progress you will see few built-in directives of AngularJs and how they acts on Model and Views.

Prerequisites
  1. Eclipse IDE with one of one of server plugins(Apache Tomcat/Jetty etc) installed. 
  2. Any web browser (Chrome,Firefox etc..)
Steps
We build the entire application step by step. Each step is concentrated on a particular functionality.
OK, let's start.

Step 1. Create a Dynamic Web project in eclipse
    File->New->Dynamic web Project
    Give the project name as "angularjs-demo" and click finish button.

Step 2. Create the first page index.html

Right click on WebContent folder ->New ->HTML File.
    Change the name to index.html and click on finish.
    Open index.html and change the <title> as you like. Here I am going to change it to "AngularJs Demo".
        <title>AngularJs Demo</title>
    Keep rest everything as it is.


Step 3. Import AngularJs

We can include AngularJS library to our application using 'script' tag.
This can be done in two ways.
  • Use the local copy of angular.min.js file
    Download the angular.js lib from https://angularjs.org/ and keep it in local application directory(Example /WebContent/lib/) .
    Copy angular.min.js file to /WebContent/lib/ project folder. (To create lib folder - Right click on WebContent and New->Folder)
    Add the script tag as below.
    <script src="lib/angular.min.js"></script>
  • Point your code directly to angular script on the Google CDN server
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>

Step 4. Create module and controller for your application


    To begin with AngularJs we need to create two things - Module and Controller.
    Controller : A controller is a JavaScript function where we write presentation logic to be applied on data and later this data is supplied to view.
    Module: A module is a container for the different parts of your app (controller,services etc).


    To put our module and controller code we are going to create a new js file specific to our application.
    Create a folder 'js' inside WebContent folder (Right click on WebContent and New->Folder).
    Create the file angulardemo.js inside js folder.(Right click on js folder -> New->File).
   
    Add the below code to angulardemo.js file.

    var app = angular.module("demoApp", []);
    app.controller("demoCtrl", function($scope) {
        $scope.book = "The Alchemist";
        $scope.author = "Paulo Coelho";
    });
 We just created a module "demoApp" and a controller for the module "demoCtrl".
    Import the angulardemo.js to index.html just like angular.min.js file.
    <script src="js/angulardemo.js"></script>
      
    Now all the files are created. Just to make sure everything is fine, below is folder structure of this application.




Step 5.  Bootstrapp the angularJs app  

    To inject the module into HTML DOM we use ng-app directive. (For now just keep in mind that directive is like an html attribute which does something special. ng-app is one of the many built in directives of AngularJs)
    ng-app can be applied to any html element like <html>,<body>,<div> etc.
   
    <html ng-app="demoApp">
    Above code indicates that all the contents inside this html tag will bind to the module "demoApp".


Step 6.  Display the model data from Controller on View
If we look inside the controller code we will see two variables defined . ie $scope.book and $scope.author. $scope is like a global object which can be accessed by both View and Controller. All the elements in $scope (here the variables book and author) can be directly used in View.

Now are going to add some plain html code to display the model data in view - index.html.Add the below code inside body element.

   <div ng-controller="demoCtrl">
        <table border="1">
            <tr>
                <td>Book Name</td>
                <td ng-bind="book"></td>
            </tr>
            <tr>
                <td>Author</td>
                <td ng-bind="author"></td>
            </tr>
        </table>
    </div>

ng-controller is another built-in directive just like ng-app which indicates that model for this <div> element will be supplied and controlled by "demoCtrl" controller.
ng-bind is the directive wich the bind the content of enclosing html element with value of the scope variable.
Here table cell <td> will be filled with actual values (defined in controller) of model variables 'book' and 'author'.

Step 7.  Run the application
    Running the application is similar to running any other web application in eclipse.
    Right click on project->Run As-> Run on Server.. (Hope you have installed Apache/Jetty or any other sever plugins in eclipse)
   
    Hit the url : http://localhost:8080/angularjs-demo/ in your web browser.
    If everything works well you will get the below output.

Complete source code
   
    index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html ng-app="demoApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AngularJs Demo</title>
<script src="lib/angular.min.js"></script>
<script src="js/angulardemo.js"></script>
</head>
<body>
 <div ng-controller="demoCtrl">
  <table border="1">
   <tr>
    <td>Book Name</td>
    <td ng-bind="book"></td>
   </tr>
   <tr>
    <td>Author</td>
    <td ng-bind="author"></td>
   </tr>
  </table>
 </div>
</body>
</html>

    angulardemo.js
var app = angular.module("demoApp", []);

app.controller("demoCtrl", function($scope) {
 $scope.book = "The Alchemist";
 $scope.author = "Paulo Coelho";
});

What you've seen so far   
  •     Directives 
               ng-app : Bootstrap and define angularJs in HTML DOM.
               ng-controller : Define a controller for html element.
               ng-bind : Bind html elements with model data.
  •     AngularJs function to create module - angular.module(....)
  •     AngularJs function to create controller - .controller(....)
  •     The bridge between controller functions and the HTML DOM  - $scope
   
This is just a beginning to AngularJs. There are many other dependent libraries and core components which are used for developing a fully functional website. Hope this is helpful in learning AngularJs. Feel free to share your comments and suggestions. Happy Learning!!



Thursday 8 October 2015

Basics of AngularJs



Why AngularJs?
There are various frameworks out there which helps us with web application development. Then why AngularJs? Here are some of the core features of AngularJs.

MVC Architecture
       AngularJs applications are built using  MVC (model–view–controller) Or MVVM (model–view–viewmodel) architecture. This ensures clear isolation between application components.

MVC is an architectural pattern which modularise business logic,presentation logic and interaction between the two. Here Model is the data (like any data object) View is presentation layer (HTML,or partial views) and Controller is a function which apply business logic and present it to view. Spring MVC is a widely used server side architecture.

The architecture followed in angularJs slight different than the conventional MVC frameworks. Here controller acts as bridge between view and model. So It is also called as MVVM (model–view–viewmodel) framework. To avoid such confusion and arguments a more common usage evolved is MVW ( Model View Whatever).

Use of more familiar HTML
  HTML is the template language in angularJs. Most of the web developers are familiar with HTML tags. AngularJs just extend the features of html using it's directives.(We will see directives in details later).

Easy Integration
AngularJs can be easily integrated to web applications by simply importing AngularJs library.
This can be done in two ways
1. Download the angular.js lib from https://angularjs.org/ and keep it in local application directory.

2. Point your code directly to angular script on the Google CDN server.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>

SPA design
  In a Single Page Application (SPA) all necessary code (HTML, CSS and JavaScript) is retrieved with a single page load. Appropriate resources are dynamically loaded and added to the page as necessary. This reduce much loading time and pages become more responsive.
AngularJs has different directives to support SPA design.

Two way data-binding
This is one of the very important feature of AngularJs. This provides synchronisation between Model and View layers. Model changes propagated to the View, and View changes are instantly reflected back in the Model. Below is the code which explains this can be implemented using plain JavaScript and AngularJs.

Problem scenario: We have an input textbox and a model object. Model object hold the value in the textbox. At any point of time these two should be in sync.

Example using javascript function
<script>
     var modelObject="";
     function syncToModel() {
      modelObject = $("#inputtextbox").val();
     }
     function syncToView(){
      $("#inputtextbox").val(modelObject);
     }
     //Assume some other function which modifies the modelObject value.
     function updateModeldata(){
      modelObject ="New value";
      //To reflect the latest value to HTML textbox call syncToView function
      syncToView();
     }
</script>
<input type=text id="inputtextbox" onchange="syncToModel()"/>
 
Using AngularJs
<input type=text id="inputtextbox" ng-model="modelObject"/>

You've just seen one of the very powerful and frequently used directive of angularJs ng-model. This does the same thing as javascript functions syncToModel and syncToView but with the essence of much reduced coding.

So that's all about the basics of AngularJs.Now create your first application - Simple AngularJs Application in eclipse.