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.
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
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="utf-8" />
- <script
- src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js">
- </script>
- <script>
- function MainController($scope) {
- $scope.date = new Date();
- }
- </script>
- </head>
- <body ng-app>
- <div ng-controller="MainController">
-
- <div style="border: 5px solid gray; width: 500px;">
- <h4>Adding Date Picker in Angular Js Page </h4>
- <input type="date" ng-model="date" value="{{ date | date: 'yyyy/MM/dd' }}" />
- <br />
- <br />
- <b>Selected Date is: </b>{{ date | date: 'dd/MM/yyyy' }}
- <br />
- </div>
- </div>
- </body>
- </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
- <!DOCTYPE html>
- <html>
- <head>
- <title>Strong Password for Angular UI Pages</title>
-
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
- <script>
- var app = angular.module("myApp", []);
- app.controller("myCtrl", function ($scope) {
-
- var strongRegularExp = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");
-
- var mediumRegularExp = new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})");
-
- $scope.checkpwdStrength = {
- "width": "150px",
- "height": "25px",
- "float": "right"
- };
-
- $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';
- }
- };
-
- });
- </script>
- </head>
- <body ng-app="myApp">
- <div ng-controller="myCtrl" style="border:5px solid gray; width:800px;">
- <div>
- <h3>Strong Password for Angular UI Pages </h3>
- </div>
- <div style="padding-left:25px;">
- <div ng-style="checkpwdStrength"></div>
- <b>Password:</b> <input type="password" ng-model="userPassword" ng-change="validationInputPwdText(userPassword)" class="class1" />
- <b> {{userPasswordstrength}}</b>
- </div>
- <br />
- <br />
- <br />
- </div>
- </body>
- </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
- <!DOCTYPE html>
- <html ng-app="app">
-
- <head>
- <meta charset="utf-8" />
- <title>Confirmation Dialog in Angular JS</title>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
- <script>
- var app = angular.module('app', []);
-
- app.controller('MainCtrl', function ($scope) {
- $scope.name = 'World';
- });
-
- app.directive('ngConfirmClick', [
- function () {
- return {
- 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)
- }
- });
- }
- };
- }])
- </script>
- </head>
-
- <body ng-controller="MainCtrl">
- <div style="border: 5px solid gray; width: 500px;">
- <h4>Showing Confirmation Dialog in Angular</h4>
- <button
- ng-confirm-click>
- Say hi to {{ name }}</button>
- <br />
- <br />
- </div>
- </body>
- </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
- <!DOCTYPE html>
- <html>
- <head>
- <link rel="stylesheet" href="style.css">
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
- <script>
- var app = angular.module('imageApp', []);
- app.controller('imageAppCtrl', function ($scope) {
- $scope.urlImage = 'image/1.jpg';
- $scope.replaceImage = function () {
- $scope.urlImage = 'image/2.jpg';
- }
- });
-
- </script>
- </head>
- <body ng-app="imageApp">
- <div style="border:5PX solid gray; width:500px;">
- <h4>Adding Image in a Angular Page</h4>
- <div ng-controller="imageAppCtrl">
- <a href='#'>
- <img ng-src="{{urlImage}}" />
- </a>
- <button ng-click="replaceImage()">Replace Image</button>
- </div>
- </div>
- </body>
- </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
- <!DOCTYPE html>
- <html ng-app="app">
- <head>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
- <script>
- var app = angular.module('app', []);
-
- app.controller('Ctrl', function ($scope, $timeout) {
-
- $scope.val = '1';
- });
- app.directive('cutCopyPaste', function () {
- return {
- scope: {},
- link: function (scope, element) {
- element.on('cut copy paste', function (event) {
- event.preventDefault();
- alert("cut copy paste is not allweed");
- })
- }
- };
- });
- </script>
- </head>
- <body ng-controller="Ctrl">
- <div style="border: 5PX solid gray; width: 500px;">
- <h4>Not allowing cut copy paste in Angular js Page</h4>
- <input cut-copy-paste ng-model="val" ng-maxlength="10" maxlength="10" />
- <br />
- <br />
- </div>
- </body>
- </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
- <!DOCTYPE html>
- <html>
- <head>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
- <script>
- var cartApp = angular.module('sCartApp', []);
- cartApp.controller('sCartCtrl', function ($scope) {
-
- $scope.ngShowhide = false;
- $scope.ngShowhideFun = function (flag) {
- if (flag) {
- $scope.ngShowhide = false;
- } else {
- $scope.ngShowhide = true;
- }
- };
- });
- </script>
- </head>
- <body ng-app="sCartApp">
- <div ng-controller="sCartCtrl" style="border: 5PX solid gray; width: 500px;">
- <a ng-click="ngShowhideFun(ngShowhide)" href="">angularjs toggle Example</a>
- <div ng-show="ngShowhide">
- <div style="background-color: yellow">
- <p>
- showing toggle demo
-
- </p>
- </div>
- <br />
- </div>
- </div>
- </body>
- </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.
- <html>
- <head>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
- <script type="text/javascript">
- var app = angular.module('app', []);
- app.controller("mainCtrl", function ($scope, $element) {
- $scope.clickme = function () {
- var elem = angular.element(document.querySelector('#txtName'));
- elem.css('color', 'red');
- elem.css('font-size', '28px');
- };
- }); </script>
- </head>
- <body ng-app="app">
- <div ng-controller="mainCtrl" style="border: 5PX solid gray; width: 500px;">
- <div>
- <h4>Manipulating DOM Element - Using JqLite</h4>
- <input type="text" id="txtName" value="" />
- <button type="button" ng-click="clickme()">Change Font and TextBox color</button>
- </div>
- <br />
- </div>
- </body>
- </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
- <!DOCTYPE html>
-
- <html ng-app="app">
-
- <head>
- <style type="text/css">
-
- </style>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
- <script>
-
- var app = angular.module('app', [], function () { })
- app.controller('FileUploadCtrl', function ($scope) {
- var dropbox = document.getElementById("dropbox")
- $scope.dropText = 'Drop files here...'
-
- function dragEnterLeave(evt) {
- evt.stopPropagation()
- evt.preventDefault()
- $scope.$apply(function () {
- $scope.dropText = 'Drop files here...'
- $scope.dropClass = ''
- })
- }
- dropbox.addEventListener("dragenter", dragEnterLeave, false)
- dropbox.addEventListener("dragleave", dragEnterLeave, false)
- dropbox.addEventListener("dragover", function (evt) {
- evt.stopPropagation()
- evt.preventDefault()
- var clazz = 'not-available'
- var ok = evt.dataTransfer && evt.dataTransfer.types && evt.dataTransfer.types.indexOf('Files') >= 0
- $scope.$apply(function () {
- $scope.dropText = ok ? 'Drop files here...' : 'Only files are allowed!'
- $scope.dropClass = ok ? 'over' : 'not-available'
- })
- }, false)
- dropbox.addEventListener("drop", function (evt) {
- console.log('drop evt:', JSON.parse(JSON.stringify(evt.dataTransfer)))
- evt.stopPropagation()
- evt.preventDefault()
- $scope.$apply(function () {
- $scope.dropText = 'Drop files here...'
- $scope.dropClass = ''
- })
- var files = evt.dataTransfer.files
- if (files.length > 0) {
- $scope.$apply(function () {
- $scope.files = []
- for (var i = 0; i < files.length; i++) {
- $scope.files.push(files[i])
- }
- })
- }
- }, false)
-
-
- $scope.setFiles = function (element) {
- $scope.$apply(function ($scope) {
- console.log('files:', element.files);
- $scope.files = []
- for (var i = 0; i < element.files.length; i++) {
- $scope.files.push(element.files[i])
- }
- $scope.progressVisible = false
- });
- };
-
- $scope.uploadFile = function () {
- var fd = new FormData();
- for (var i in $scope.files) {
- fd.append("uploadedFile", $scope.files[i])
- }
- var xhr = new XMLHttpRequest();
- xhr.upload.addEventListener("progress", uploadProgress, false);
- xhr.addEventListener("load", uploadComplete, false);
- xhr.addEventListener("error", uploadFailed, false);
- xhr.addEventListener("abort", uploadCanceled, false);
- xhr.open("POST", "api/upload"); //Web API or service call here.
- $scope.progressVisible = true;
- xhr.send(fd);
- };
-
- function uploadProgress(evt) {
- $scope.$apply(function () {
- if (evt.lengthComputable) {
- $scope.progress = Math.round(evt.loaded * 100 / evt.total)
- } else {
- $scope.progress = 'unable to compute'
- }
- })
- }
-
- function uploadComplete(evt) {
- /* This event is raised when the server send back a response */
- // alert(evt.target.responseText)
- alert("uploaded");
- }
-
- function uploadFailed(evt) {
- alert("There was an error attempting to upload the file.")
- }
-
- function uploadCanceled(evt) {
- $scope.$apply(function () {
- $scope.progressVisible = false
- })
- alert("The upload has been canceled by the user or the browser dropped the connection.")
- }
- });
-
- </script>
- </head>
- <body ng-controller="FileUploadCtrl">
-
- <div style="width:600px;border: 2px solid gray;">
- <div class="row">
- <label for="fileToUpload"><b>File Uploader In Angular Js</b></label><br />
- <input type="file" ng-model-instant id="fileToUpload" multiple onchange="angular.element(this).scope().setFiles(this)" />
- </div>
- <div id="dropbox" class="dropbox" ng-class="dropClass"><span>{{dropText}}</span></div>
- <div ng-show="files.length">
- <div ng-repeat="file in files.slice(0)">
- <span>{{file.webkitRelativePath || file.name}}</span>
- (<span ng-switch="file.size > 1024*1024">
- <span ng-switch-when="true">{{file.size / 1024 / 1024 | number:2}} MB</span>
- <span ng-switch-default>{{file.size / 1024 | number:2}} kB</span>
- </span>)
- </div>
- <input type="button" ng-click="uploadFile()" value="Upload" />
- <div ng-show="progressVisible">
- <div class="percent">{{progress}}%</div>
- <div class="progress-bar">
- <div class="uploaded" ng-style="{'width': progress+'%'}"></div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </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
- <!DOCTYPE html>
- <html ng-app="app">
- <head>
- <title>Submitting a form on clicking Enter key</title>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
- <script type="text/javascript">
- angular.module('app').directive('ngEnter', function () {
- return function (scope, element, attrs) {
- element.bind("keydown keypress", function (event) {
- if (event.which === 13) {
- scope.$apply(function () {
- scope.$eval(attrs.ngEnter);
- });
- event.preventDefault();
- }
- });
- };
- });
- </script>
- </head>
- <body ng-app="app">
- <form name="name" class="form">
- <input type="text" ng-model="model.term" />
- <button type="submit" class="btn">Submit</button>
- </form>
- </body>
- </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
- <!doctype html>
- <html ng-app="app">
- <head>
-
- <title>Add Row dynamically</title>
-
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
-
- <script type="text/javascript">
-
- var ng = angular.module('app', []);
-
- ng.controller('controller', function ($scope) {
-
- $scope.rows = []; // declared rows and assigned a empty row to the scope
-
- $scope.addDynamically = function () {
-
- $scope.rows.push({
- FirstName: "Fist Name",
- LastName: "Last Name",
- IsActive: true,
- Save: "Save",
-
- }); //Added the values to scopes which need to be added
- };
- });
- </script>
- <body>
-
- <h4>Adding Controls Dynamically in Angular Js </h4>
-
- <div ng-controller="controller" style="border:5px solid gray;width:500px;">
-
- <button ng-click="addDynamically()" style="color:blue;font-size:18px;">Add New Row Dynamically</button>
- <div>
- <br />
- <input type="text" placeholder="Fist Name">
-
- <input type="text" placeholder="Last Name">
-
- <input type="checkbox" name="check" value="inline">IsActive
- <input type="Button" name="check" value="Save" placeholder="Save">
- </div>
-
- <div ng-repeat="row in rows">
-
- <input type="text" placeholder="{{row.FirstName}}">
-
- <input ng-class="{'blockInput': !row.IsActive}" placeholder="{{row.LastName}}" type="text">
-
- <input type="checkbox" name="check" value="inline">IsActive
- <input type="Button" placeholder="{{row.LastName}}" value="Save">
- </div>
- <br/>
- </div>
- </body>
- </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!