numbersOnly Text Box Directive In AngularJS

Introduction

Directive in AngularJS is very powerful concept. Directives allow the developers to design any kind of controls or components in AngularJS, which can be used in HTML as an attribute, element, etc. That provides us great flexibility.
 
I will explain here how to create a custom directive that allows only numbers in a text box. Then, the text box will not accept any string or even special characters.
 
Given below is the program defining the directive.
  1. var app = angular.module("myModule");  
  2.   
  3. app.directive("numbersOnly"function () {  
  4.     return {  
  5.         require: 'ngModel',  
  6.         link: function (scope, element, attr, ngModelCtrl) {  
  7.             function fromUser(text) {  
  8.                 if (text) {  
  9.                     var transformedInput = text.replace(/[^0-9]/g, '');  
  10.   
  11.                     if (transformedInput !== text) {  
  12.                         ngModelCtrl.$setViewValue(transformedInput);  
  13.                         ngModelCtrl.$render();  
  14.                     }  
  15.                     return transformedInput;  
  16.                 }  
  17.                 return undefined;  
  18.             }  
  19.             ngModelCtrl.$parsers.push(fromUser);  
  20.         }  
  21.     };  
  22. });  
You can use the numbersOnly directive as shown in the above code. Here, we have defined "require" type as "ngModel". Also, I have applied regex "/[^0-9]/g". This attribute allows entering only the numbers into the text box.
 
The require:'ngModel' allows developer to inject the model attached to the element or its parent element on which the directive is bound to.
Its basically an easiest way to pass ngModel into the link/compile function instead passing it using a scope option. Once you have access to ngModel, you can change its value using $setViewValue, make it dirty/clean using $formatters, apply watchers, etc.
 
Load this directive into index.html file and use it like the below code in your text box.
  1. <input type="text"  
  2.          class="textFields" placeholder="Amount" ng-model="contactUsController.amount"  
  3.          numbers-only />  
Conclusion

AngularJS directive is a very powerful feature. It provides great flexibility in the designing of any control or component, which provides modularization and re-usability.
Ebook Download
View all
Learn
View all