Pages

Monday 2 November 2015

Simple Login page using AngularJs Bootstrap and Grunt

        In this tutorial we are going to create a simple Login page using AngularJs Bootstrap and Grunt. Here we don't use any grunt per-written templates. We create the application from the very base so that you get the clear picture of this application.

This is the login page that we are going to implement.



Prerequisites
Download and install NodeJs and Git.

1. NodeJs  : https://nodejs.org/en/download/
2. Git     : https://git-scm.com/downloads

Step 1. Create the directory structure
Create the following folder structure.
- demoapplication/
    --src/
    --src/common/
    --src/demoapp/

demoapplication - is the root folder of this project. (You can give any name..)
src - Contains application's source files. Later we fill this up with HTML,CSS and JS files.

Step 2. Set up npm dependencies
        npm (Node Package manager) manages dependencies for an application. We specify the npm configuration in a meta data file  package.json. To create package.json go to project root folder (Here demoapplication/) and run the below command.

> npm init

You will be prompted to enter certain values like name,version etc. Give relevant values and hit Enter.
Finally npm will show a full package.json file an asks you 'Is this OK? (yes)'
Give yes and continue.

Now add the dependencies for the application. Open package.json and add devDependencies as below.
"devDependencies": {
    "grunt": "^0.4.5",
    "grunt-angular-templates": "^0.5.7",
    "grunt-bower-concat": "^0.6.0",
    "grunt-contrib-clean": "^0.6.0",
    "grunt-contrib-concat": "^0.5.1",
    "grunt-contrib-connect": "^0.11.2",
    "grunt-contrib-copy": "^0.8.2",
    "grunt-contrib-watch": "^0.6.1",
    "load-grunt-tasks": "^3.3.0"
    }
To install the packages run the below command.

> npm install

This will take few minutes to download all the dependencies. You can see the installed packages inside /demoapplication/node_modules directory.

Step 3. Configure bower Dependencies
        Similar to npm , bower is also a package manager and is optimized for the front-end web applications.
Here we add dependencies like bootstrap,angularJs etc which are required for proper working of application.The config file for bower is bower.json. Create this file by running the command.

> bower init

Fill the details like package.json and create bower.json.
Now add the dependencies to bower.json.
"dependencies": {
    "angular": "~1.4.7",
    "angular-route": "~1.4.7",
    "bootstrap": "~3.3.5"
  }
Finally install the package using below command.

> bower install

You can see the installed packages inside bower_components folder.

Step 4. Develop login page using AngularJs and apply css bootstrap styles

Our application will have the following files.
index.html - First page where we load all the js/css etc and bootstrap AngularJs application.
header.html - Header menu using CSS bootstrap nav bar.
login page - Simple login page in plain html.

Now create the following files.
  1. src/index.html
  2. src/common/header.html
  3. src/demoapp/demoapp.css
  4. src/demoapp/demoapp.html
  5. src/demoapp/demoapp.js
Below is the source code of each file.
1.index.html
<html ng-app="demoapp">
 <head>
  <title>Demo Application</title>
  
  <link rel="stylesheet" type="text/css" href="css/bower.css">
  <link rel="stylesheet" type="text/css" href="css/app.css">

  <script src="js/bower.js"></script>
  <script src="js/app.js"></script>
  <script src="js/templates.js"></script>
 </head>
 <body>
  <div ng-include='"src/common/header.html"'></div>
  <div ng-view></div>
 </body>
</html>

2.header.html
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
  <div class="container-fluid">
   <div class="navbar-header">
   </div> 
    <a class="navbar-brand" href="http://tutorialbasics.blogspot.in">TutorialBasics</a>
   </div>
</nav>

3.demoapp.css
body {
   padding-top: 100px; 
   text-align: center;
   background-color:#F4F4F4;
}
.login-form {
    background-color: #E4E4E4;
}

4.demoapp.html
<div class="container">    
    <div class="col-md-5 col-md-offset-3">                    
        <div class="panel panel-primary" >
            <div class="panel-heading">
                <div class="panel-title">Account Login</div>
            </div>     

            <div class="panel-body login-form" >
                <input type="text" class="form-control" placeholder="username or email" />
                </br>
                <input type="text" class="form-control" placeholder="password" />
                </br>

                <div class="form-group">
                    <input type="checkbox"> Remember me
                </div>        

                <div class="form-group">
                    <input type="button" class="btn btn-lg btn-success btn-block" value="Sign in">
                </div>

            </div>
        </div>
    </div>
</div>

5.demoapp.js
var demoapp =  angular.module('demoapp',['ngRoute']);

demoapp.config(['$routeProvider',function($routeProvider){
 $routeProvider.when('/demoapp',{
  templateUrl: 'src/demoapp/demoapp.html',
        controller: 'demoController'
  
 }).otherwise({ redirectTo: '/demoapp' });
}]);

demoapp.controller('demoController',function($scope){
 //controller code here...
});


Step 5. Configure Grunt


Grunt is a JavaScript task runner. Tasks includes minify files,validate files,combine files,start server and many more.
All these tasks can be automated and trigger using single command.

Grunt uses a configuration file (Gruntfile) where we define the tasks and order in which they run.
Gruntfile can be either Gruntfile.js or Gruntfile.coffee. Here we use Gruntfile.js.

Create Gruntfile.js file inside project root directory (demoapplication/). Open Gruntfile.js and add the below content.

Gruntfile.js
'use strict';
module.exports = function(grunt) {
  require('load-grunt-tasks')(grunt);
  
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    /*watch - watch the files for modification and trigger the build*/
    watch: {
      options: {
        livereload: true,
      },
      src: {
        files: [
        'src/**/*.*',
        ],
        tasks: ['build']
      },

      gruntfile: {
        files: ['Gruntfile.js']
      }
    },

  /*connect - open server at localhost and liveupdate contents*/
    connect: {
      options: {
        port: 9000,
        hostname: 'localhost',
      },
      livereload: {
        options: {
          open: true,
          base: 'deploy'
        }
      }
    },

  /*copy - copy index.html to deploy folder*/
    copy: {
      build: {
        cwd: 'src',
        src: [ 'index.html' ],
        dest: 'deploy/',
        expand: true
      }
    },

    /*clean - clean the deploy directory*/
    clean: {
      build: {
        src: [ 'deploy' ]
      },
    },

    /*concat - concat all js/css files into single file*/
    concat: {
      options: {
        separator: ';'
      },
      appjs: {
        src: ['src/**/*.js'],
        dest: 'deploy/js/app.js'
      },
      appcss: {
        src: ['src/**/*.css'],
        dest: 'deploy/css/app.css'
      },

      bowercss: {
        src: ['bower_components/**/*.css'],
        dest: 'deploy/css/bower.css'
      },
    },

    /*bower_concat - concat all js files inside bower_components directory*/
    bower_concat: {
      all: {
        dest: 'deploy/js/bower.js',
      }
    },

    /*ngtemplates - put all html files into templateCache and generate as single js file*/
    ngtemplates: {
      options: {
        base: "deploy",
        module: "demoapp",
      },
      app:        {
        src:      'src/**/*.html',
        dest:     'deploy/js/templates.js'
      }
    }

  });

grunt.registerTask('build', [
  'clean',
  'concat',
  'bower_concat',
  'ngtemplates',
  'copy'
  ]);

grunt.registerTask('default', [
  'build',
  'connect',
  'watch'
  ]);

};

You will see many tasks defined in Gruntfile.js file. These tasks are implemented in npm dependencies that we added in Step 2.
Below is the list of tasks and it's purpose.

Task
npm package
use
clean
grunt-contrib-clean
To clean the final deploy directory
copy
grunt-contrib-copy
Copy files to deploy folder (Here only one file index.html)
concat
grunt-contrib-concat
Concat - concat all js/css files into single file
bower_concat
grunt-bower-concat
Concat all js files inside bower_components directory
ngtemplates
grunt-angular-templates
Put all html files into templateCache and generate as single js file
connect
grunt-contrib-connect
Open server at localhost and live update contents
watch
grunt-contrib-watch
Watch the files for modification

grunt.registerTask registers task,sub tasks and order of execution.Two tasks are registered here- build and default.The build task contains other sub tasks like clean,concat etc. default is the main task which will run the application.

Step 6. Run the application

Now everything is set for running the application. Before that make sure you have all the folder/files in the below structure.

To run the application type the below command in cmd from project root( demoapplication/)

> grunt 

This will automatically build and copy the files to deploy folder and open the login page in your web browser as we saw in the beginning.
URL to demoapp - http://localhost:9000/#/demoapp 

Few points to remember
  • Live load: If we change any files inside src folder same will be reflected automatically in web page. (No page refresh needed).
  • Always make sure you update files inside src folder only (Don't update the files under deploy folder).
  • All the html files are compiled to templates.js file( You won't see any html files inside deploy folder. grunt-angular-templates does this trick).
That's it. Hope this will be handy application to begin with. Feel free to share your comments and feedback.

Git repo : https://github.com/tutorialbasics/login-demo.git


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.