AngularJS Text - Allow Numeric Only

In this blog, I will demonstrate how to allow only numeric values in input textbox, using AngularJS. This technique is most useful for quantity and countable input text.

HTML Code

I have designed a simple input type “Text” in HTML.using AngularJS.

  1. <div class="panel panel-primary">  
  2.       <div class="panel-heading">  
  3.         <h3 class="panel-title">AngularJS Text Allow Numeric Only</h3>  
  4.       </div>  
  5.       <div class="panel-body">  
  6.        <input type="text"   
  7.             class="form-control"  
  8.             ng-model="TextValues" />  
  9.       </div>  
  10.       <div class="panel-footer">  
  11.     {{TextValues}}  
  12.     </div>  
  13.     </div>  

AngularJS Code

Create an Angular module and name it as  "csharpcor".
  1. var app = angular.module('csharpcor', []);  
Create Angular Controller for initiating the value.
  1. app.controller('NgCtrl', function($scope) {  
  2.   $scope.TextValues=123456789;   
  3. });  
Module and Controller name must assign to the HTML element.
  1. <html ng-app="'csharpcor'" ng-controller="NgCtrl">  

Create Angular directives as given below.

  1. app.directive('numericonly', function () {  
  2.     return {  
  3.         require: 'ngModel',  
  4.         link: function (scope, element, attr, ngModelCtrl) {  
  5.             function fromUser(text) {  
  6.                 var transformedInput = text.replace(/[^0-9]/g, '');  
  7.                 if (transformedInput !== text) {  
  8.                     ngModelCtrl.$setViewValue(transformedInput);  
  9.                     ngModelCtrl.$render();  
  10.                 }  
  11.                 return transformedInput;   
  12.             }  
  13.             ngModelCtrl.$parsers.push(fromUser);  
  14.         }  
  15.     };  
  16. });  
 Assgin a directive to the input text.
  1. <input type="text"   
  2.      numericonly  
  3.      class="form-control"  
  4.      ng-model="TextValues" />  
Output

Ebook Download
View all
Learn
View all