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