Common Hands-on Samples For AngularJS Developers: Part 2

This article gives you some hands-on samples in AngularJs. In every web application, we use some common functionality that is frequently used in pages or modules. Let us see what these common requirements are and how to create them.

Note: There can be other ways of satisfying this requirement. I have written this article based on my learning. For visualizing the requirements, I have added the output first and then written the code below.

If you have not gone through part one, please go through Common Hands-on Sample For AngularJS Developers: Part 1.
 
Example-1

Adding Date picker in AngularJs

There are many scenarios where we need to add a date picker for fields, like Date of Birth, Start Date, End Date, Due Date and so on. Here it is shown in the following code.

Code
  1. <!doctype html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <script  
  6.         src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js">    
  7.     </script>  
  8.     <script>  
  9.         function MainController($scope) {  
  10.             $scope.date = new Date();  
  11.         }  
  12.     </script>  
  13. </head>  
  14. <body ng-app>  
  15.     <div ng-controller="MainController">  
  16.   
  17.         <div style="border: 5px solid gray; width: 500px;">  
  18.             <h4>Adding Date Picker in Angular Js Page </h4>  
  19.             <input type="date" ng-model="date" value="{{ date | date: 'yyyy/MM/dd' }}" />  
  20.             <br />  
  21.             <br />  
  22.             <b>Selected Date is: </b>{{ date | date: 'dd/MM/yyyy' }}     
  23.             <br />  
  24.         </div>  
  25.     </div>  
  26. </body>  
  27. </html>  

Code Clarification

<input type="date" ng-model="date" value="{{ date | date: 'yyyy/MM/dd' }}" />

function MainController($scope) {

$scope.date = new Date();

}

ng-model="date" takes the field of date type and assign the date picker.

Example-2

Checking a strong password in AngularJs

We must have seen a password field where we need a combination of special characters, capital letters, small letters, digits and so on. Here is a sample of how to prompt the user to show the password strength.

 Code
  1. <!DOCTYPE html>    
  2. <html>    
  3. <head>    
  4.     <title>Strong Password for Angular UI Pages</title>    
  5.         
  6.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>      
  7.     <script>  
  8.         var app = angular.module("myApp", []);  
  9.         app.controller("myCtrl", function ($scope) {  
  10.   
  11.             var strongRegularExp = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");  
  12.   
  13.             var mediumRegularExp = new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})");  
  14.   
  15.             $scope.checkpwdStrength = {  
  16.                 "width": "150px",  
  17.                 "height": "25px",  
  18.                 "float": "right"  
  19.             };  
  20.   
  21.             $scope.validationInputPwdText = function (value) {  
  22.                 if (strongRegularExp.test(value)) {  
  23.                     $scope.checkpwdStrength["background-color"] = "green";  
  24.                     $scope.userPasswordstrength = 'You have a Very Strong Password now';  
  25.                 } else if (mediumRegularExp.test(value)) {  
  26.                     $scope.checkpwdStrength["background-color"] = "orange";  
  27.                     $scope.userPasswordstrength = 'Strong password, Please give a very strong password';  
  28.                 } else {  
  29.                     $scope.checkpwdStrength["background-color"] = "red";  
  30.                     $scope.userPasswordstrength = 'Weak Password , Please give a strong password';  
  31.                 }  
  32.             };  
  33.   
  34.         });  
  35.     </script>    
  36. </head>    
  37. <body ng-app="myApp">    
  38.     <div ng-controller="myCtrl" style="border:5px solid gray; width:800px;">    
  39.         <div>    
  40.             <h3>Strong Password for Angular UI Pages </h3>    
  41.         </div>    
  42.         <div style="padding-left:25px;">    
  43.             <div ng-style="checkpwdStrength"></div>    
  44.            <b>Password:</b> <input type="password" ng-model="userPassword" ng-change="validationInputPwdText(userPassword)" class="class1" />    
  45.             <b> {{userPasswordstrength}}</b>    
  46.         </div>    
  47.         <br />    
  48.         <br />    
  49.         <br />    
  50.     </div>    
  51. </body>    
  52. </html>    

Code Clarification


The code validates the user inputs using a Regex and prompts with an appropriate message and colour code for that.

$scope.validationInputPwdText = function (value) {

if (strongRegularExp.test(value)) {

$scope.checkpwdStrength["background-color"] = "green";

$scope.userPasswordstrength = 'You have a Very Strong Password now';

} else if (mediumRegularExp.test(value)) {

$scope.checkpwdStrength["background-color"] = "orange";

$scope.userPasswordstrength = 'Strong password, Please give a very strong password';

} else {

$scope.checkpwdStrength["background-color"] = "red";

$scope.userPasswordstrength = 'Weak Password , Please give a strong password';

}

}; });

Example-3

Showing a Confirmation Dialog

Before doing an insert, update, delete or before posting some event we have often seen it needs a confirmation from the user. Here is how we need to show a confirmation message.

 

Code

  1. <!DOCTYPE html>  
  2. <html ng-app="app">  
  3.   
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <title>Confirmation Dialog in Angular JS</title>  
  7.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>  
  8.     <script>  
  9.         var app = angular.module('app', []);  
  10.   
  11.         app.controller('MainCtrl', function ($scope) {  
  12.             $scope.name = 'World';  
  13.         });  
  14.   
  15.         app.directive('ngConfirmClick', [  
  16.                 function () {  
  17.                     return {  
  18.                         link: function (scope, element, attr) {  
  19.                             var msg = attr.ngConfirmClick || "Are you sure?";  
  20.                             var clickAction = attr.confirmedClick;  
  21.                             element.bind('click', function (event) {  
  22.                                 if (window.confirm(msg)) {  
  23.                                     scope.$eval(clickAction)  
  24.                                 }  
  25.                             });  
  26.                         }  
  27.                     };  
  28.                 }])  
  29.     </script>  
  30. </head>  
  31.   
  32. <body ng-controller="MainCtrl">  
  33.     <div style="border: 5px solid gray; width: 500px;">  
  34.         <h4>Showing Confirmation Dialog in Angular</h4>  
  35.         <button  
  36.             ng-confirm-click>  
  37.             Say hi to {{ name }}</button>  
  38.         <br />  
  39.         <br />  
  40.     </div>  
  41. </body>  
  42. </html>  

Code Clarification

Create a custom directive ng-confirm-click and bind to the element in the link function as given below.

link: function (scope, element, attr) {

var msg = attr.ngConfirmClick || "Are you sure?";

var clickAction = attr.confirmedClick;

element.bind('click', function (event) {

if (window.confirm(msg)) {

scope.$eval(clickAction)

}

});

Example-4

Adding an image to angular page

It is very common to need to add an image to a page.

 

Code

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <link rel="stylesheet" href="style.css">  
  5.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>  
  6.     <script>  
  7.         var app = angular.module('imageApp', []);  
  8.         app.controller('imageAppCtrl', function ($scope) {  
  9.             $scope.urlImage = 'image/1.jpg';  
  10.             $scope.replaceImage = function () {  
  11.                 $scope.urlImage = 'image/2.jpg';  
  12.             }  
  13.         });  
  14.   
  15.     </script>  
  16. </head>  
  17. <body ng-app="imageApp">  
  18.     <div style="border:5PX solid gray; width:500px;">  
  19.         <h4>Adding Image in a Angular Page</h4>  
  20.         <div ng-controller="imageAppCtrl">  
  21.             <a href='#'>  
  22.                 <img ng-src="{{urlImage}}" />  
  23.             </a>  
  24.             <button ng-click="replaceImage()">Replace Image</button>  
  25.         </div>  
  26.     </div>  
  27. </body>  
  28. </html>  

Code Clarification

<img ng-src="{{urlImage}}" />, urlImage comes from scope.

Example-5

Not allow the user to cut, copy and paste in AngularJs.

 
 Code
  1. <!DOCTYPE html>  
  2. <html ng-app="app">  
  3. <head>  
  4.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>  
  5.     <script>  
  6.         var app = angular.module('app', []);  
  7.   
  8.         app.controller('Ctrl', function ($scope, $timeout) {  
  9.   
  10.             $scope.val = '1';  
  11.         });  
  12.         app.directive('cutCopyPaste', function () {  
  13.             return {  
  14.                 scope: {},  
  15.                 link: function (scope, element) {  
  16.                     element.on('cut copy paste', function (event) {  
  17.                         event.preventDefault();  
  18.                         alert("cut copy paste is not allweed");  
  19.                     })  
  20.                 }  
  21.             };  
  22.         });  
  23.     </script>  
  24. </head>  
  25. <body ng-controller="Ctrl">  
  26.     <div style="border: 5PX solid gray; width: 500px;">  
  27.         <h4>Not allowing cut copy paste in Angular js Page</h4>  
  28.         <input cut-copy-paste ng-model="val" ng-maxlength="10" maxlength="10" />  
  29.         <br />  
  30.         <br />  
  31.     </div>  
  32. </body>  
  33. </html>  

Code Clarification

Create a custom directive for cut, copy & paste and bind it to the element.

Example-6

Toggle a text in AngularJs

Let us see how to toggle text.
 

Code

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>  
  5.     <script>  
  6.         var cartApp = angular.module('sCartApp', []);  
  7.         cartApp.controller('sCartCtrl', function ($scope) {  
  8.   
  9.             $scope.ngShowhide = false;  
  10.             $scope.ngShowhideFun = function (flag) {  
  11.                 if (flag) {  
  12.                     $scope.ngShowhide = false;  
  13.                 } else {  
  14.                     $scope.ngShowhide = true;  
  15.                 }  
  16.             };  
  17.         });  
  18.     </script>  
  19. </head>  
  20. <body ng-app="sCartApp">  
  21.     <div ng-controller="sCartCtrl" style="border: 5PX solid gray; width: 500px;">  
  22.         <a ng-click="ngShowhideFun(ngShowhide)" href="">angularjs toggle Example</a>  
  23.         <div ng-show="ngShowhide">  
  24.             <div style="background-color: yellow">  
  25.                 <p>  
  26.                     showing toggle demo  
  27.   
  28.                 </p>  
  29.             </div>  
  30.             <br />  
  31.         </div>  
  32.     </div>  
  33. </body>  
  34. </html>  

Code Clarification

Toggle the text using the ngShowhide method using the ng-show method.

Example-7

Doing a DOM manipulation –Using JqLite

Many times we will use custom directives to manipulate the DOM. Here we need to manipulate without creating a directive.  Here we have a TextBox when a user enters some text and clicks "Change Font and TextBox color", the text will be changed as given below.

 

Code

  1. <html>  
  2. <head>  
  3.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>  
  4.     <script type="text/javascript">  
  5.         var app = angular.module('app', []);  
  6.         app.controller("mainCtrl", function ($scope, $element) {  
  7.             $scope.clickme = function () {  
  8.                 var elem = angular.element(document.querySelector('#txtName'));  
  9.                 elem.css('color', 'red');  
  10.                 elem.css('font-size', '28px');  
  11.             };  
  12.         }); </script>  
  13. </head>  
  14. <body ng-app="app">  
  15.     <div ng-controller="mainCtrl" style="border: 5PX solid gray; width: 500px;">  
  16.         <div>  
  17.             <h4>Manipulating DOM Element - Using JqLite</h4>  
  18.             <input type="text" id="txtName" value="" />  
  19.             <button type="button" ng-click="clickme()">Change Font and TextBox color</button>  
  20.         </div>  
  21.         <br />  
  22.     </div>  
  23. </body>  
  24. </html>  

Code Clarification

Reading the element using angular.element as var elem = angular.element(document.querySelector('#txtName')); and applying styles into it.

Example-8

File upload with progress Bar

Sometimes we need to upload some documents using a file uploader and show the progress bar. Here is a sample directive that does that.
 

Code

  1. <!DOCTYPE html>  
  2.   
  3. <html ng-app="app">  
  4.   
  5. <head>  
  6.     <style type="text/css">  
  7.         
  8.     </style>  
  9.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>  
  10.     <script>  
  11.   
  12.         var app = angular.module('app', [], function () { })  
  13.         app.controller('FileUploadCtrl', function ($scope) {  
  14.             var dropbox = document.getElementById("dropbox")  
  15.             $scope.dropText = 'Drop files here...'  
  16.   
  17.             function dragEnterLeave(evt) {  
  18.                 evt.stopPropagation()  
  19.                 evt.preventDefault()  
  20.                 $scope.$apply(function () {  
  21.                     $scope.dropText = 'Drop files here...'  
  22.                     $scope.dropClass = ''  
  23.                 })  
  24.             }  
  25.             dropbox.addEventListener("dragenter", dragEnterLeave, false)  
  26.             dropbox.addEventListener("dragleave", dragEnterLeave, false)  
  27.             dropbox.addEventListener("dragover", function (evt) {  
  28.                 evt.stopPropagation()  
  29.                 evt.preventDefault()  
  30.                 var clazz = 'not-available'  
  31.                 var ok = evt.dataTransfer && evt.dataTransfer.types && evt.dataTransfer.types.indexOf('Files') >= 0  
  32.                 $scope.$apply(function () {  
  33.                     $scope.dropText = ok ? 'Drop files here...' : 'Only files are allowed!'  
  34.                     $scope.dropClass = ok ? 'over' : 'not-available'  
  35.                 })  
  36.             }, false)  
  37.             dropbox.addEventListener("drop", function (evt) {  
  38.                 console.log('drop evt:', JSON.parse(JSON.stringify(evt.dataTransfer)))  
  39.                 evt.stopPropagation()  
  40.                 evt.preventDefault()  
  41.                 $scope.$apply(function () {  
  42.                     $scope.dropText = 'Drop files here...'  
  43.                     $scope.dropClass = ''  
  44.                 })  
  45.                 var files = evt.dataTransfer.files  
  46.                 if (files.length > 0) {  
  47.                     $scope.$apply(function () {  
  48.                         $scope.files = []  
  49.                         for (var i = 0; i < files.length; i++) {  
  50.                             $scope.files.push(files[i])  
  51.                         }  
  52.                     })  
  53.                 }  
  54.             }, false)  
  55.   
  56.   
  57.             $scope.setFiles = function (element) {  
  58.                 $scope.$apply(function ($scope) {  
  59.                     console.log('files:', element.files);  
  60.                     $scope.files = []  
  61.                     for (var i = 0; i < element.files.length; i++) {  
  62.                         $scope.files.push(element.files[i])  
  63.                     }  
  64.                     $scope.progressVisible = false  
  65.                 });  
  66.             };  
  67.   
  68.             $scope.uploadFile = function () {  
  69.                 var fd = new FormData();  
  70.                 for (var i in $scope.files) {  
  71.                     fd.append("uploadedFile", $scope.files[i])  
  72.                 }  
  73.                 var xhr = new XMLHttpRequest();  
  74.                 xhr.upload.addEventListener("progress", uploadProgress, false);  
  75.                 xhr.addEventListener("load", uploadComplete, false);  
  76.                 xhr.addEventListener("error", uploadFailed, false);  
  77.                 xhr.addEventListener("abort", uploadCanceled, false);  
  78.                 xhr.open("POST", "api/upload"); //Web API or service call here.  
  79.                 $scope.progressVisible = true;  
  80.                 xhr.send(fd);  
  81.             };  
  82.   
  83.             function uploadProgress(evt) {  
  84.                 $scope.$apply(function () {  
  85.                     if (evt.lengthComputable) {  
  86.                         $scope.progress = Math.round(evt.loaded * 100 / evt.total)  
  87.                     } else {  
  88.                         $scope.progress = 'unable to compute'  
  89.                     }  
  90.                 })  
  91.             }  
  92.   
  93.             function uploadComplete(evt) {  
  94.                 /* This event is raised when the server send back a response */  
  95.                 //  alert(evt.target.responseText)  
  96.                 alert("uploaded");  
  97.             }  
  98.   
  99.             function uploadFailed(evt) {  
  100.                 alert("There was an error attempting to upload the file.")  
  101.             }  
  102.   
  103.             function uploadCanceled(evt) {  
  104.                 $scope.$apply(function () {  
  105.                     $scope.progressVisible = false  
  106.                 })  
  107.                 alert("The upload has been canceled by the user or the browser dropped the connection.")  
  108.             }  
  109.         });  
  110.   
  111.     </script>  
  112. </head>  
  113. <body ng-controller="FileUploadCtrl">  
  114.   
  115.     <div style="width:600px;border: 2px solid gray;">  
  116.         <div class="row">  
  117.             <label for="fileToUpload"><b>File Uploader In Angular Js</b></label><br />  
  118.             <input type="file" ng-model-instant id="fileToUpload" multiple onchange="angular.element(this).scope().setFiles(this)" />  
  119.         </div>  
  120.         <div id="dropbox" class="dropbox" ng-class="dropClass"><span>{{dropText}}</span></div>  
  121.         <div ng-show="files.length">  
  122.             <div ng-repeat="file in files.slice(0)">  
  123.                 <span>{{file.webkitRelativePath || file.name}}</span>  
  124.                 (<span ng-switch="file.size > 1024*1024">  
  125.                     <span ng-switch-when="true">{{file.size / 1024 / 1024 | number:2}} MB</span>  
  126.                     <span ng-switch-default>{{file.size / 1024 | number:2}} kB</span>  
  127.                 </span>)  
  128.             </div>  
  129.             <input type="button" ng-click="uploadFile()" value="Upload" />  
  130.             <div ng-show="progressVisible">  
  131.                 <div class="percent">{{progress}}%</div>  
  132.                 <div class="progress-bar">  
  133.                     <div class="uploaded" ng-style="{'width': progress+'%'}"></div>  
  134.                 </div>  
  135.             </div>  
  136.         </div>  
  137.     </div>  
  138. </body>  
  139. </html>  

Example-9

Submitting a form on pressing Enter on KeyBoard

Many web forms allow us to submit the form on pressing the Enter key. Let us submit a form on hitting the “Enter” key. Observe the "?" here in the browser URL.

 
Code
  1. <!DOCTYPE html>  
  2. <html ng-app="app">  
  3. <head>  
  4.     <title>Submitting a form on clicking Enter key</title>  
  5.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>  
  6.     <script type="text/javascript">  
  7.         angular.module('app').directive('ngEnter', function () {  
  8.             return function (scope, element, attrs) {  
  9.                 element.bind("keydown keypress", function (event) {  
  10.                     if (event.which === 13) {  
  11.                         scope.$apply(function () {  
  12.                             scope.$eval(attrs.ngEnter);  
  13.                         });  
  14.                         event.preventDefault();  
  15.                     }  
  16.                 });  
  17.             };  
  18.         });  
  19.     </script>  
  20. </head>  
  21. <body ng-app="app">  
  22.     <form name="name" class="form">  
  23.         <input type="text" ng-model="model.term" />  
  24.         <button type="submit" class="btn">Submit</button>  
  25.     </form>  
  26. </body>  
  27. </html>  

Code Clarification

Create a directive “'ngEnter' and bind it to the event code 13, the key press event.

Example-10

Adding a row dynamically in a page or section in AngularUI

Many times we need to create a TextBox, check box, button and so on to be created in a row at runtime depending upon some condition. Let us see how we need to do this.

 

Code

  1. <!doctype html>    
  2. <html ng-app="app">    
  3. <head>    
  4.     
  5.     <title>Add Row dynamically</title>    
  6.     
  7.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>      
  8.     
  9.     <script type="text/javascript">  
  10.   
  11.         var ng = angular.module('app', []);  
  12.   
  13.         ng.controller('controller', function ($scope) {  
  14.   
  15.             $scope.rows = []; // declared rows and assigned a empty row to the scope     
  16.   
  17.             $scope.addDynamically = function () {  
  18.   
  19.                 $scope.rows.push({  
  20.                     FirstName: "Fist Name",  
  21.                     LastName: "Last Name",  
  22.                     IsActive: true,  
  23.                     Save: "Save",  
  24.   
  25.                 }); //Added the values to scopes which need to be added     
  26.             };  
  27.         });  
  28.     </script>    
  29.     <body>    
  30.     
  31.         <h4>Adding Controls Dynamically in Angular Js </h4>    
  32.     
  33.         <div ng-controller="controller" style="border:5px solid gray;width:500px;">    
  34.     
  35.             <button ng-click="addDynamically()" style="color:blue;font-size:18px;">Add New Row Dynamically</button>    
  36.             <div>    
  37.                 <br />    
  38.                 <input type="text" placeholder="Fist Name">    
  39.     
  40.                 <input type="text" placeholder="Last Name">    
  41.     
  42.                 <input type="checkbox" name="check" value="inline">IsActive    
  43.                 <input type="Button" name="check" value="Save" placeholder="Save">    
  44.             </div>    
  45.     
  46.             <div ng-repeat="row in rows">    
  47.                  
  48.                 <input type="text" placeholder="{{row.FirstName}}">    
  49.     
  50.                 <input ng-class="{'blockInput': !row.IsActive}" placeholder="{{row.LastName}}" type="text">    
  51.     
  52.                 <input type="checkbox" name="check" value="inline">IsActive    
  53.                 <input type="Button" placeholder="{{row.LastName}}"  value="Save">    
  54.             </div>    
  55.             <br/>    
  56.         </div>    
  57.     </body>    
  58. </html>    

Code Clarification

Here we are calling  the function addDynamically that pushes the value to scope.

We have now completed 10 hands-on examples that are commonly used in any project. I hope this will be useful!

Up Next
    Ebook Download
    View all
    Learn
    View all