Skip to main content

Automatic Slashing the Date Input using Angularjs

We define a directive that will automatically slash the input field as user typein the date. The directive have following capabiltiy:
  • The directive will append slash '/' when input field has 2 or 5 characters.
  • The input will accept only 10 characters (dd/mm/yyyy).
  • Validity of date provide will not be checked.
  • When the backspace is pressed it will remove the last two character if last character is slash. Otherwise it will remove last character from the input field.
  • The input will not accept characters other than numbers (0 to 9).
Let's jump into the code. We will use bootstrap for awesome look:
HTML Code:

<div class="container" ng-app="myApp" ng-controller="myAppCtrl">
 <div class="row">
  <div class="col-sm-8 col-sm-offset-2">
   <form class="form-horizontal">
    <h4 class="bg-primary">Auto Slashing Date using Angularjs Directive</h4>
    <div class="form-group">
     <label for="date1" class="col-sm-3 control-label">Date:</label>
     <div class="col-sm-3">
      <input type="text" id="date1" class="form-control" name="date1" ng-model="date1" placeholder="dd/mm/yyyy" auto-slash>
     </div>
     <label class="col-sm-3 control-label">{{date1}}</label>
    </div> 
   </form>
  </div>
 </div>
</div>
Javascript Code:

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

app.controller('myAppCtrl',['$scope',function($scope){
 $scope.date1 = '';
}]);
/*This directive auto slash the input field.
It will not check the validity of date provide into dd/dd/dddd format*/
app.directive('autoSlash',[function(){
 return {
  require : 'ngModel',
  link : function(scope, iElement, iAttribute, ngModelController){
   iElement.on('keydown',function(e){
    var key = e.keyCode;
    if(key === 8){ /* If backspace is pressed*/
     if(this.value.length === 3 || this.value.length === 6){
      /*if next char to be removed is /' remove last two characters from input value*/
      this.value = this.value.substr(0, this.value.length-1);
     }
     /*remove last character*/
     this.value = this.value.substr(0, this.value.length);
    }
    /*if key pressed is not number or input got date*/
    else if( !((key > 47 && key < 58) || (key > 95 && key < 106)) 
       || this.value.length === 10){
     e.preventDefault(); //do nothing
    }
   });

   function autoSlash(veiwvalue){
    if(veiwvalue.length === 2 || veiwvalue.length === 5){
     veiwvalue += '/';
    }
    ngModelController.$setViewValue(veiwvalue);
    ngModelController.$render(); //change DOM
    if(veiwvalue.length === 10){
     return veiwvalue;
    }
   }

   ngModelController.$parsers.push(autoSlash);
  }
 };
}]);
Here we have defined an autoSlash directive. This directive has a capabily to capture the keydown event on the input field where it is attached. If the key is backspace, then it will perform necessary action as per requirment. It will prevent other key stroke other than numeric and backspace. As the key stroke happens and inputs value changes, the $parsers array function autoSlash() will fire and append the slash '/' at the end if the length of value of input field is either 2 or 5. $setViewValue() function defined on ngModelController will update the $viewValue and $render() will update the DOM.

Working Example:

Comments

  1. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.
    Visit Us: http://www.zerobugacademy.com/angularjs-training-in-chennai

    ReplyDelete
  2. You rock particularly for the high caliber and results-arranged offer assistance. I won't reconsider to embrace your blog entry to anyone who needs and needs bolster about this region. We are providing angularJs training in velchery.
    for more details:AngularJs training in chennai

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete

Post a Comment

Popular posts from this blog

$parsers and $formatters in Angularjs

$parsers and $formatters are array of function defined on ngModelController . When there is change in values (view or model), the value is passed through the $parsers or $formatters pipeline to convert it according to the needs. $parsers (View to Model): $parsers is an array of function which executes when there is change in view  value ( $veiwValue ), usually via user input. $parsers cause the conversion of view value into the form desirable to assign in model value. The value is passed through each $parsers function and the return value of one function is passed to next function. Last return value is passed to $validators and after validation the value is assigned to model. These $parsers functions are called array order (i.e. index 0 to n). $parsers are not called when there is change in model value programmatically. $parsers function must return some value. If it not, causes parse error and model value is set to undefined . Let's see the simple ...

Auto generating the year in select using ngOption

While creating an angular form, we come upon a situation where we required to generate the sequence of years in the select HTML tag. There is some way to perform this task, but each has its limitation. Let's look the way to generate the years : Hard code an array having years in your controller and assign it to some $scope variable. Use for loop to generate the years and then assign to $scope variable. Send $http request to generate the array of year and assign the response data to $scope variable. Define a filter that will be used to generate the sequence of years. As the first and second method makes our controller dirty and the third method causes HTTP request that will overhead server, so we are going to see the fourth method to generate the years as it has several advantages over other three methods. So let's jump into the code: HTML Code: <form name="myform"> <select ng-options="year for year in [] | range: '2000':'20...