European Windows 2019 Hosting BLOG

BLOG about Windows 2019 Hosting and SQL 2019 Hosting - Dedicated to European Windows Hosting Customer

AngularJS Hosting - HostForLIFE.eu :: AES Encryption/Decryption With Angular 7

clock February 15, 2019 10:15 by author Peter

Most of the time, a developer requires encryption and decryption for encoding a message or information in such a way that only authorized person can retrieve that information.
In this article, I will discuss the implementation of AES encryption and decryption with Angular 7 while developing an application.

So, the first question that comes in our mind is "What is AES?".
AES stands for "Advanced Encryption Standard".
It is a tool that is used to encrypt and decrypt the simple text using AES encryption algorithm.
This algorithm was developed by two Belgian cryptographers, Joan Daemen and Vincent Rijmen.
AES was designed to be efficient in both, hardware and software, and supports a block length of 128 bits and key lengths of 128, 192, and 256 bits.

When to use AES Encryption

When you want to encrypt a confidential text into a decryptable format, for example - when you need to send some sensitive data in an e-mail.
The decryption of the encrypted text is possible only if you know the right password.

Now, try to implement the AES encryption and decryption in Angular 7. It's very easy to implement in Angular 7 with the help of crypto-js.

First, we create a new project with the following command.
ng new EncryptionDescryptionSample 

After that, install crypto.js file, by the following command.
npm install crypto-js --save 

For better UI, we also install bootstrap by the following command.
npm install bootstrap --save 

After running the above command, check the package.json file if it is installed or not. Your file should look like this.
AES Encryption/Decryption with Angular 7

Now, go to "app.component.html" file and replace the existing code with the below code.
<h1 class="text-center">Encrypt-Decrypt with AES</h1> 
 
<br> 
<div> 
  <div class="row"> 
    <div class="col-sm-6"> 
      <button type="button" class="btn btn-primary btn-lg btn-block"> 
        Encryption 
      </button> 
      <br> 
      <div class="form-group"> 
        <label for="txtTextToConvert">Plain Text</label> 
        <input type="text" class="form-control" placeholder="Enter text you want to encrypt" [(ngModel)]="plainText"> 
      </div> 
 
      <div class="form-group"> 
        <label for="txtPassword">Password</label> 
        <input type="password" class="form-control" placeholder="Enter encryption password" [(ngModel)]="encPassword"> 
      </div> 
      <textarea class="form-control" readonly rows="3">{{conversionEncryptOutput}}</textarea> 
      <br> 
      <button type="button" class="btn btn-success float-right" (click)="convertText('encrypt')">Encrypt</button> 
    </div> 
    <div class="col-sm-6"> 
      <button type="button" class="btn btn-dark btn-lg btn-block"> 
        Decryption 
      </button> 
      <br> 
      <div class="form-group"> 
        <label for="txtTextToConvert">Encrypted Text</label> 
        <input type="text" class="form-control" placeholder="Enter text you want to decrypt" [(ngModel)]="encryptText"> 
      </div> 
 
      <div class="form-group"> 
        <label for="txtPassword">Password</label> 
        <input type="password" class="form-control" placeholder="Enter decryption password" [(ngModel)]="decPassword"> 
      </div> 
      <textarea class="form-control" readonly rows="3">{{conversionDecryptOutput}}</textarea> 
      <br> 
      <button type="button" class="btn btn-success float-right" (click)="convertText('decrypt')">Decrypt</button> 
    </div> 
  </div> 
</div> 


Now, visit "app.component.ts" file and write the below code,
import { Component } from '@angular/core'; 
import * as CryptoJS from 'crypto-js'; 
 
@Component({ 
  selector: 'app-root', 
  templateUrl: './app.component.html', 
  styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
  title = 'EncryptionDecryptionSample'; 
   
  plainText:string; 
  encryptText: string; 
  encPassword: string; 
  decPassword:string; 
  conversionEncryptOutput: string; 
  conversionDecryptOutput:string; 
   
  constructor() { 
  } 
  //method is used to encrypt and decrypt the text 
  convertText(conversion:string) { 
      if (conversion=="encrypt") { 
        this.conversionEncryptOutput = CryptoJS.AES.encrypt(this.plainText.trim(), this.encPassword.trim()).toString(); 
      } 
      else { 
        this.conversionDecryptOutput = CryptoJS.AES.decrypt(this.encryptText.trim(), this.decPassword.trim()).toString(CryptoJS.enc.Utf8); 
      
    } 
  } 


In the above code, we used the Encrypt method of AES and passed our plain text with a password to encrypt the string. Similarly, we used the Decrypt method of AES and passed our encrypted text with a password to decrypt the string. Be sure that both times, your password is the same. For using both of these methods, you need to import "CryptoJS" from crypto-js.
import * as CryptoJS from 'crypto-js'; 

Now, let us run the project by using the following command.
ng serve --o 

HostForLIFE.eu AngularJS Hosting

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

 



AngularJS Hosting - HostForLIFE.eu :: How to Create Cascading Dropdown in AngularJS?

clock January 16, 2019 11:50 by author Peter

In this post, I will make a Cascading Dropdown in AngularJS. Add 2 Class 1 for Countries and other for state. Write the following code:
public class Country 

    public int CountryId { get; set; } 
    public string CountryName { get; set; } 

public class State 

    public int StateId { get; set; } 
    public string StateName { get; set; } 
    public int CountryId { get; set; } 

Create a ActionResult Name it as Index [Add a View].

Add the script

<script src="~/Scripts/angular.min.js"></script> 

Create a js Name it in my case its CascadingDropdown.

var app = angular.module('myApp', []); 
app.controller('myController', function ($scope, $http) { 
    getcountries(); 
    function getcountries() { 
     
        $http({ 
            method: 'Get', 
            url: '/Home/Countries' 
 
        }).success(function (data, status, header, config) { 
 
            $scope.countries = data; 
        }).error(function (data, status, header, config) { 
            $scope.message = "Error"; 
        }); 
    } 
 
    $scope.GetStates = function ()  
    { 
        var countryIdselected = $scope.countrymodel; 
        if (countryIdselected) { 
            $http({ 
                method: 'Post', 
                url: '/Home/States', 
                data: JSON.stringify({ countryId: countryIdselected }) 
            }).success(function (data, status, header, config) { 
                $scope.states = data; 
            }).error(function (data, status, header, config) { 
                $scope.message = "Error"; 
            }) 
        } 
        else { 
            $scope.states = null; 
        } 
    } 
}); 
 
 
//Calls for Country DropDown 
 public ActionResult Countries() 
        { 
            List<Country> cobj = new List<Country>(); 
            cobj.Add(new Country { CountryId = 1, CountryName = "India" }); 
            cobj.Add(new Country { CountryId = 2, CountryName = "Srilanka" }); 
            cobj.Add(new Country { CountryId = 3, CountryName = "USA" }); 
 
            return Json(cobj, JsonRequestBehavior.AllowGet); 
        } 
 
//Calls for State DropDown with CountryID as Parameter 
 
        public ActionResult States(int countryId) 
        { 
   List<State> sobj = new List<State>(); 
   sobj.Add(new State { StateId = 1, StateName = "Karnataka", CountryId = 1 }); 
   sobj.Add(new State { StateId = 2, StateName = "Kerala", CountryId = 1 }); 
   sobj.Add(new State { StateId = 3, StateName = "TamilNadu", CountryId = 1 }); 
   sobj.Add(new State { StateId = 1, StateName = "Newyork", CountryId = 3 }); 
   sobj.Add(new State { StateId = 1, StateName = "Colombo", CountryId = 2 }); 
 
//Filter based on CountryID 
            var result = sobj.Where(x => x.CountryId == countryId).Select(x => new { x.StateId, x.StateName }); 
 
            return Json(result); 
        } 
 
//IndexView 
//  Add the script file <script src="~/Scripts/CascadingDropdown.js"></script> 
<div ng-app="myApp"> 
       
            <form name="mainForm"  ng-controller="myController"> 
 
                <select ng-model="countrymodel" ng-options=" c.CountryId as c.CountryName for c in countries" ng-change="GetStates()"> 
                    <option value="">-- Select Country --</option> 
                </select> 
                <select ng-model="statemodel" ng-options="s.StateId as s.StateName for s in states "> 
                    <option value="">-- Select State --</option> 
                </select> 
            </form> 
</div>  


I hope it works for you!

HostForLIFE.eu AngularJS Hosting

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



AngularJS Hosting - HostForLIFE.eu :: AngularJs ng-repeat

clock November 2, 2016 08:32 by author Peter

Angular js URL:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> 

Html tag:
<div ng-app="myApp" ng-controller="myCntrl"> 
    <table> 
        <thead> 
            <tr> 
                <th> 
                    Emp Code. 
                </th> 
                <th> 
                    Employee Name 
                </th> 
                <th> 
                    Pan No 
                </th> 
                  
            </tr> 
        </thead> 
        <tr ng-repeat="student in EmployeeList"> 
            <td ng-bind="student.StudentID"> 
            </td> 
            <td ng-bind="student.StudentName"> 
            </td> 
            <td ng-bind="student.PanNO"> 
            </td> 
              
        </tr> 
    </table> 
</div> 

Angular js Script :

<script> 
   var app = angular.module("myApp", []); 
   app.controller("myCntrl", function ($scope, $http) { 

       $scope.fillList = function () { 
           $scope.EmployeeName = ""; 
           var httpreq = { 
               method: 'POST', 
               url: 'Default2.aspx/GetList', 
               headers: { 
                   'Content-Type': 'application/json; charset=utf-8', 
                   'dataType': 'json' 
               }, 
               data: {} 
           } 
           $http(httpreq).success(function (response) { 
               $scope.EmployeeList = response.d; 
           }) 
       }; 
       $scope.fillList(); 
   }); 
</script> 


Asp.net Cs page code:
using System; 
using System.Collections.Generic; 
using System.Data.SqlClient; 
using System.Data; 

public partial class Default2 : System.Web.UI.Page 

protected void Page_Load(object sender, EventArgs e) 



[System.Web.Services.WebMethod()] 
public static List<Employee> GetList() 

    List<Employee> names = new List<Employee>(); 
    DataSet ds = new DataSet(); 
    using (SqlConnection con = new SqlConnection(@"Data Source=140.175.165.10;Initial Catalog=Payroll_290716;user id=sa;password=Goal@12345;")) 
    { 
        using (SqlCommand cmd = new SqlCommand()) 
        { 
            cmd.Connection = con; 
            cmd.CommandText = "select EmpId,Empcode, name,PanNo from EMPLOYEEMASTER  order by Name;"; 
            using (SqlDataAdapter da = new SqlDataAdapter(cmd)) 
            { 
                da.Fill(ds); 
            } 
        } 
    } 
    if (ds != null && ds.Tables.Count > 0) 
    { 
        foreach (DataRow dr in ds.Tables[0].Rows) 
            names.Add(new Employee(int.Parse(dr["EmpId"].ToString()), dr["name"].ToString(), dr["PanNo"].ToString())); 
    } 
    return names; 


public class Employee 

public int StudentID; 
public string StudentName; 
public string PanNO; 
public Employee(int _StudentID, string _StudentName, string _PanNO) 

    StudentID = _StudentID; 
    StudentName = _StudentName; 
    PanNO = _PanNO; 

}  


Whole HTML page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title></title> 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div ng-app="myApp" ng-controller="myCntrl"> 
    <table> 
        <thead> 
            <tr> 
                <th> 
                    Emp Code. 
                </th> 
                <th> 
                    Employee Name 
                </th> 
                <th> 
                    Pan No 
                </th> 
                  
            </tr> 
        </thead> 
        <tr ng-repeat="student in EmployeeList"> 
            <td ng-bind="student.StudentID"> 
            </td> 
            <td ng-bind="student.StudentName"> 
            </td> 
            <td ng-bind="student.PanNO"> 
            </td> 
              
        </tr> 
    </table> 
</div> 
<script> 
    var app = angular.module("myApp", []); 
    app.controller("myCntrl", function ($scope, $http) { 

        $scope.fillList = function () { 
            $scope.EmployeeName = ""; 
            var httpreq = { 
                method: 'POST', 
                url: 'Default2.aspx/GetList', 
                headers: { 
                    'Content-Type': 'application/json; charset=utf-8', 
                    'dataType': 'json' 
                }, 
                data: {} 
            } 
            $http(httpreq).success(function (response) { 
                $scope.EmployeeList = response.d; 
            }) 
        }; 
        $scope.fillList(); 
    }); 
</script> 
</form> 
</body> 
</html>  

HostForLIFE.eu AngularJS Hosting

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



AngularJS Hosting - HostForLIFE.eu :: Ng-options from other Uses of Same ng-Options

clock August 23, 2016 21:54 by author Peter

In this post, i will tell you about ng ng-options instance but remove the selected items from previous uses in Angularjs. Now write the following code:

    <!DOCTYPE html> 
    <html> 
     
    <head> 
        <title></title> 
        <meta charset="utf-8" /> 
        <script src="Scripts/angular.js"></script> 
        <link href="Content/bootstrap.css" rel="stylesheet" /> 
        <script> 
    var app = angular.module('myApp', []); 
    app.controller('demoCtrl', function ($scope) 
    { 
        $scope.options = [ 
        { 
            name: 'Apple', 
            id: '1' 
        }, 
        { 
            name: 'Orange', 
            id: '2' 
        }, 
        { 
            name: 'Banana', 
            id: '3' 
        }, 
        { 
            name: 'Pear', 
            id: '4' 
        }, ]; 
    }); 
        </script> 
    </head> 
     
    <body> 
        <div ng-app="myApp" ng-controller="demoCtrl"> 
            <div class="form-group col-md-3"> 
                <label for="select1">Select 1:</label> 
                <select ng-model="newForm.select1" ng-options="option.name as option.name for option in options" class="form-control"> 
                    <option value=""></option> 
                </select> 
            </div> 
            <div class="row"> 
                <br> </div> 
            <div class="form-group col-md-3"> 
                <label for="select2">Select 2:</label> 
                <select ng-model="newForm.select2" ng-options="option.name as option.name for option in options | filter: newForm.select1 && {name: '!' + newForm.select1}" class="form-control"> 
                    <option value=""></option> 
                </select> 
            </div> 
        </div> 
    </body> 
     
    </html> 

 

HostForLIFE.eu AngularJS Hosting

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



AngularJS Hosting - HostForLIFE.eu :: How to Datatable Binding Using AngularJS?

clock March 30, 2016 00:05 by author Peter

Today I want to show you how to Datatable Binding Using AngularJS. Now write the following code:
<html xmlns="http://www.w3.org/1999/xhtml"> 

  <head> 
      <title>Datatable Records Using AngularJS</title> 
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script> 
      <script src="http://ui-grid.info/release/ui-grid-unstable.js"></script> 
      <link rel="stylesheet" href="http://ui-grid.info/release/ui-grid-unstable.css" type="text/css"> 
      <script type="text/javascript"> 
      debugger; 
      var myApp = angular.module('sampleapp', ['ui.grid', 'ui.grid.selection', 'ui.grid.exporter']); 
      myApp.controller("appcontroller", function ($scope, $http) 
      { 
          $scope.gridOptions = { 
              data: 'BindDataTableusingJSON', 
              columnDefs: [ 
              { 
                  field: 'Application_Number' 
              }, 
              { 
                  field: 'Candidate_Name' 
              }, 
              { 
                  field: 'Category' 
              }, 
              { 
                  field: 'Fathers_Name' 
              }, 
              { 
                  field: 'Date' 
              }, 
              { 
                  field: 'Address' 
              }] 
          }; 
          $scope.BindDataTableusingJSON = { 
              "data": [] 
          }; 
          $http.post('try2.aspx/SaveUser', 
              { 
                  data: 
                  {} 
              }) 
              // $http.get('try2.aspx/SaveUser') 
              .success(function (data) 
              { 
                  debugger; 
                  // var data = jQuery.parseJSON(data.d.toString()); 
                  var d = JSON.parse(data.d); 
                  $scope.BindDataTableusingJSON = d; 
              }); 
      }).config(function ($httpProvider) 
      { 
          $httpProvider.defaults.headers.post = {}; 
          $httpProvider.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8"; 
      }); 
      </script> 
      <style type="text/css"> 
      .grid { 
          width: 800px; 
          height: 400px; 
      } 
       
      .nodatatxt { 
          position: absolute; 
          top: 80px; 
          opacity: 0.25; 
          font-size: 1.5em; 
          width: 100%; 
          text-align: center; 
          z-index: 1000; 
      } 
      </style> 
  </head> 

  <body> 
      <form id="form1" runat="server"> 
          <div ng-app="sampleapp" ng-controller="appcontroller"> 
              <br /> 
              <br /> 
              <div ui-grid="gridOptions" ui-grid-selection ui-grid-exporter class="grid"> 
                  <div class="nodatatxt" ng-if="BindDataTableusingJSON.data.length==0"> No Records Found</div> 
              </div> 
          </div> 
      </form> 
  </body> 

</html> 

Code-behind

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data; 
using System.Web.Script.Serialization; 
using System.Web.Services; 
using System.Web.Script.Services; 
public partial class Services_t_try2: System.Web.UI.Page 

  protected void Page_Load(object sender, EventArgs e) 
  {} 
  [WebMethod] 
  [ScriptMethod] 
  public static string SaveUser() 
  { 
      DataSet ds = YourFunctionWhichReturnsDataset(); 
      DataTable dt = ds.Tables[0]; 
      ds.Tables[0].Columns[4].ColumnName = ds.Tables[0].Columns[4].ColumnName.Replace("Date Of Birth", "Date"); 
      return DataTableToJSONWithJavaScriptSerializer(ds.Tables[0]); 
  } 
  public static string DataTableToJSONWithJavaScriptSerializer(DataTable table) 
  { 
      JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); 
      List < Dictionary < string, object >> parentRow = new List < Dictionary < string, object >> (); 
      Dictionary < string, object > childRow; 
      foreach(DataRow row in table.Rows) 
      { 
          childRow = new Dictionary < string, object > (); 
          foreach(DataColumn col in table.Columns) 
          { 
              childRow.Add(col.ColumnName, row[col]); 
          } 
          parentRow.Add(childRow); 
      } 
      return jsSerializer.Serialize(parentRow); 
  } 

 

HostForLIFE.eu AngularJS Hosting

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



AngularJS Hosting - HostForLIFE.eu :: How to create Strong Password for AngularJS?

clock March 3, 2016 21:33 by author Peter

This code snippet helps us in choosing a strong password for AngularJS UI pages. All of us have seen , for choosing a password we need combination of special characters, Capital letter , small letters, digits etc to make it strong.

Write the following 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>  
    <input type="password" ng-model="userPassword" ng-change="validationInputPwdText(userPassword)" class="class1" />  
    <b> {{userPasswordstrength}}</b>  
</div>  
<br />  
<br />  
<br />  
</div>  
</body>  
</html>  

HostForLIFE.eu AngularJS Hosting

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



AngularJS Hosting - HostForLIFE.eu :: User Validation with Bootstrap in AngularJS

clock October 8, 2015 12:11 by author Peter

AngularJS forms and controls can validate input data. AngularJS forms and controls can provide validation services, and notify users of invalid input. In this tutorial, we will learn how to perform user validation with bootstrap in AngularJS.

HTML code
var app = angular.module('myapp', ['UserValidation']); 
myappCtrl = function($scope) { 
$scope.formAllGood = function () { 
return ($scope.usernameGood && $scope.passwordGood && $scope.passwordCGood) 




angular.module('UserValidation', []).directive('validUsername', function () { 
return { 
require: 'ngModel', 
link: function (scope, elm, attrs, ctrl) { 
ctrl.$parsers.unshift(function (viewValue) { 
    // Any way to read the results of a "required" angular validator here? 
    var isBlank = viewValue === '' 
    var invalidChars = !isBlank && !/^[A-z0-9]+$/.test(viewValue) 
    var invalidLen = !isBlank && !invalidChars && (viewValue.length < 5 || viewValue.length > 20) 
    ctrl.$setValidity('isBlank', !isBlank) 
    ctrl.$setValidity('invalidChars', !invalidChars) 
    ctrl.$setValidity('invalidLen', !invalidLen) 
    scope.usernameGood = !isBlank && !invalidChars && !invalidLen 

}) 


}).directive('validPassword', function () { 
return { 
require: 'ngModel', 
link: function (scope, elm, attrs, ctrl) { 
ctrl.$parsers.unshift(function (viewValue) { 
    var isBlank = viewValue === '' 
    var invalidLen = !isBlank && (viewValue.length < 8 || viewValue.length > 20) 
    var isWeak = !isBlank && !invalidLen && !/(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z])/.test(viewValue) 
    ctrl.$setValidity('isBlank', !isBlank) 
    ctrl.$setValidity('isWeak', !isWeak) 
    ctrl.$setValidity('invalidLen', !invalidLen) 
    scope.passwordGood = !isBlank && !isWeak && !invalidLen 

}) 


}).directive('validPasswordC', function () { 
return { 
require: 'ngModel', 
link: function (scope, elm, attrs, ctrl) { 
ctrl.$parsers.unshift(function (viewValue, $scope) { 
    var isBlank = viewValue === '' 
    var noMatch = viewValue != scope.myform.password.$viewValue 
    ctrl.$setValidity('isBlank', !isBlank) 
    ctrl.$setValidity('noMatch', !noMatch) 
    scope.passwordCGood = !isBlank && !noMatch 
}) 


}) 

JAVASCRIPT Code

var app = angular.module('myapp', ['UserValidation']); 

myappCtrl = function($scope) { 
$scope.formAllGood = function () { 
return ($scope.usernameGood && $scope.passwordGood && $scope.passwordCGood) 




angular.module('UserValidation', []).directive('validUsername', function () { 
return { 
require: 'ngModel', 
link: function (scope, elm, attrs, ctrl) { 
ctrl.$parsers.unshift(function (viewValue) { 
    // Any way to read the results of a "required" angular validator here? 
    var isBlank = viewValue === '' 
    var invalidChars = !isBlank && !/^[A-z0-9]+$/.test(viewValue) 
    var invalidLen = !isBlank && !invalidChars && (viewValue.length < 5 || viewValue.length > 20) 
    ctrl.$setValidity('isBlank', !isBlank) 
    ctrl.$setValidity('invalidChars', !invalidChars) 
    ctrl.$setValidity('invalidLen', !invalidLen) 
    scope.usernameGood = !isBlank && !invalidChars && !invalidLen 

}) 


}).directive('validPassword', function () { 
return { 
require: 'ngModel', 
link: function (scope, elm, attrs, ctrl) { 
ctrl.$parsers.unshift(function (viewValue) { 
    var isBlank = viewValue === '' 
    var invalidLen = !isBlank && (viewValue.length < 8 || viewValue.length > 20) 
    var isWeak = !isBlank && !invalidLen && !/(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z])/.test(viewValue) 
    ctrl.$setValidity('isBlank', !isBlank) 
    ctrl.$setValidity('isWeak', !isWeak) 
    ctrl.$setValidity('invalidLen', !invalidLen) 
    scope.passwordGood = !isBlank && !isWeak && !invalidLen 

}) 


}).directive('validPasswordC', function () { 
return { 
require: 'ngModel', 
link: function (scope, elm, attrs, ctrl) { 
ctrl.$parsers.unshift(function (viewValue, $scope) { 
    var isBlank = viewValue === '' 
    var noMatch = viewValue != scope.myform.password.$viewValue 
    ctrl.$setValidity('isBlank', !isBlank) 
    ctrl.$setValidity('noMatch', !noMatch) 
    scope.passwordCGood = !isBlank && !noMatch 
}) 


}) 


If you fill with the wrong detail then it'll give the error like the following picture:

HostForLIFE.eu AngularJS Hosting

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



AngularJS Hosting - HostForLIFE.eu :: Learn How to Make a Directive to Allow only Numbers using AngularJs

clock August 5, 2015 08:36 by author Peter

Before reading this text there is only one prerequisite condition; you must know how to create a directive in AngularJs and why we need to create them. First of all you need to add AngularJs and jQuery to your page, similar to here:
<head runat="server"> 
<title></title> 
<script src="angular.min.js"></script> 
<script src="jquery-1.11.1.min.js"></script> 
</head>

You will either download them from my code that is available at the start of this article or you can download from their official websites. Now i'm simply adding a textbox wherever i would like to allow only numbers using an AngularJs directive.
<body> 
<form ng-app="app" id="form1" runat="server"> 
<div>
<h3> Demo to Allow Numbers Only </h3>
<hr /> 
Provide Your Mobile Number: <input type="text" 
name="MobileNumber" 
class="form-control" 
allow-only-numbers /> 
<hr /> 
</div> 
</form> 
</body>

Now it's time for Angular code. Write the following code:
<script> 
var app = angular.module('app', []); 
app.directive('allowOnlyNumbers', function () { 
return { 
restrict: 'A', 
link: function (scope, elm, attrs, ctrl) { 
elm.on('keydown', function (event) { 
if (event.which == 64 || event.which == 16) { 
// to allow numbers 
return false; 
} else if (event.which >= 48 && event.which <= 57) { 
// to allow numbers 
return true; 
} else if (event.which >= 96 && event.which <= 105) { 
// to allow numpad number 
return true; 
} else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) { 
// to allow backspace, enter, escape, arrows 
return true; 
} else { 
event.preventDefault(); 
// to stop others 
return false; 

}); 


}); 
</script>


Here I first created a module named "app". The module creation is a necessary part if you wish to use Angular. This module is added to the HTML page using the ng-app directive. Then I created the directive with the name "allowOnlyNumbers". If you're making any kind of directive using AngularJs then you need to continually check that the name is provided using "-" in your HTML page and these dashes "-" are replaced by capital letters in the Angular code. Since I had applied this directive to the attribute of the textbox I had restricted this directive using "A" for Attribute.

I had applied this directive on the keydown event of the textbox. After those varied conditions are applied to the ASCII values of the keys to permit or to prevent them. In any case our ASCII values aren't allowed. event.preventDefault() will take away that character and can revert to the previous value. But still I had the intense problem of all the characters that were entered by pressing the shift + key weren't removed by this code, therefore I used easy jQuery at the beginning of the code to help prevent this situation.
var $input = $(this); 
var value = $input.val(); 
value = value.replace(/[^0-9]/g, '') 
$input.val(value); 


Then, write the following code:
app.directive('allowOnlyNumbers', function () { 
return { 
restrict: 'A', 
link: function (scope, elm, attrs, ctrl) { 
elm.on('keydown', function (event) { 
var $input = $(this); 
var value = $input.val(); 
value = value.replace(/[^0-9]/g, '') 
$input.val(value); 
if (event.which == 64 || event.which == 16) { 
    // to allow numbers 
    return false; 
} else if (event.which >= 48 && event.which <= 57) { 
    // to allow numbers 
    return true; 
} else if (event.which >= 96 && event.which <= 105) { 
    // to allow numpad number 
    return true; 
} else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) { 
    // to allow backspace, enter, escape, arrows 
    return true; 
} else { 
    event.preventDefault(); 
    // to stop others 
    //alert("Sorry Only Numbers Allowed"); 
    return false; 

}); 


}); 


Output:
Now our application is made and we will check the output. On running the application an easy textbox are going to be shown wherever only numbers are allowed.

If you press the numbers from anywhere within the key, they will be allowed however all the other characters won't be allowed to exist, although they're special characters.

HostForLIFE.eu AngularJS Hosting

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



European AngularJS Hosting - UK :: Why Use AngularJS for Web Development

clock March 5, 2015 06:50 by author Scott

AngularJS Introduction

AngularJs is an open source Javascript framework to organise and assist web applications and single page applications. In 2012 we witnessed rise of Javascript MVC frameworks and libraries including Backbone.js , Ember.js and Angular.js.

AngularJS is created by Google to build single page applications which could be more architectured and maintainable. AngularJS is completely client-side and entirely JavaScript, so wherever Javascript runs AngularJS also runs. It is even less than 29kb making it highly minified and compressed. Angular is the next generation framework , in which every tool is designed such that it works with every other tool in an interconnected way.

Interesting Point Using AngularJS

Angular has some compelling features for not just the developers but for designers as well.

Two Way Data Binding
It is the most crucial and useful feature of Angular. This feature is what all modern web apps are all about i.e Real Time. Two way binding permanently binds the view to the model and reduces refresh cycles, it also saves a considerable amount of code as previously 80% of code was dedicated to manipulating, traversing and listening to DOM . With data binding this code disappears and hence more concentration can be laid to application. Normally with change in model the DOM elements and attributes need to be manually manipulated to reflect the changes, it proves to be a complex process mainly when application grows in complexity and in size. But with two way data binding the synchronization between the DOM and the model is well taken care of.

HTML Template
AngularJS doesn’t rely on any rendering engine but uses browser parseable .html files for its partials. The HTML templates are parsed by the browser in the DOM. The DOM is now the input to the AngularJS compiler . Angular then traverses the DOM template for rendering called the Directives. The input here is bowser DOM and not the HTML string , this is the noticeable change between angular and all fellow frameworks.

Directives
Directives are stand alone reusable elements separated from the app . All DOM manipulations are performed by Directives. Directives are used to create custom HTML tags to serve as new custom widgets .With Directive you can create a new HTML tag or attribute and make it do anything you want . Directives are very unique, useful, powerful and reusable feature available only in angular. With Directives you can invent new HTML syntax that are specific to your application.

Dependency Injection
Dependency Injection is an angular feature that enables developers to easily build, develop, test and manage applications . With this feature you merely ask for for the dependencies instead of making manually , it will provide you an instance for any service asked provided you add the service as a parameter to get access to this service.

Testing
AngularJS is designed by keeping testability in mind such that angular applications can be tested easily as any Javascript code comes with a strong set of tests . Angular comes with a end to end test runner setup .

Why Use AngularJS?

AngularJS is a new Javascript framework by Google and is designed to make front end development easier . The popularity of single page applications and angular is flaming. Angular provides numerous concepts to to organize and manipulate the web applications.

Enabling a Parallel Workflow
It enables a parallel workflow between designers and developers. For a project both designing and hard coded developing can go side by side. For a project that is estimated to be completed in 4 months then by following the traditional sequential approach there would be dedicated 4 months of design followed by 4 months of coding making it 8 months altogether. But XAML allows to work in parallel by agreeing upon an interface for a screen. Developers can work on grabbing the data and writing all properties and tests around them while designers can animate and manipulate until they reach their final desired design . Those not familiar with XAML it is a declarative XML based language to instantiate object graphs and set values. The reason XML became so popular is because they translate well to angular.

Handling Dependencies
AngularJS easily handles dependency injections , angular lets you divide your app into modules that are initialized separately and having dependencies on each other. This enables you to test only the modules you want at once while also unfolding the ability to create end to end tests as well.

Dynamic loading is used by single page applications to deliver native app feel, but it involves a lot of dependencies on various modules and services, angular organises these and even manages the lifetime of an object for you.

Declarative UI
Having a declarative UI has many advantages associated with it. A structured UI is always easier to understand and manipulate. Without ,then by mere looking at the markup it can’t be figured what UI will actually do. So its not apparent whether any translations and validations are taking place by looking at some form tags.

But by declaring UI and by directly placing markup in HTML one can understand the extended markup angular provides. It makes it clear where and to what data is being bound to. With added tools like filters and directives the intent of UI is much clearer.

Development <-> Design Workflow
This works very well with angular, markup can be added without breaking an application as it depends on a particular structure or id to locate element and do task. Even rearrangement of code is much easier as the corresponding code that binds with it also moves along.

Flexibility with Filters
Filters are standalone functions and filter the data before reaching the view, it can involve formatting decimal places or reversing an array or simply implementing pagination. Filters are separate from app just like directives and are so resourceful that creation of a sorted HTML table is possible with filters without writing any Javascript.

These fundamental features and principles will let you create a performance driven, maintainable , extensible and efficient front end codebase . AngularJS provides a rich experience to the end user, it is a robust and well maintained Javascript framework suitable for any professional web development.

 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in