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.
- <div class="panel panel-primary">
- <div class="panel-heading">
- <h3 class="panel-title">AngularJS Text Allow Numeric Only</h3>
- </div>
- <div class="panel-body">
- <input type="text"
- class="form-control"
- ng-model="TextValues" />
- </div>
- <div class="panel-footer">
- {{TextValues}}
- </div>
- </div>
AngularJS Code
Create an Angular module and name it as "csharpcor".
- var app = angular.module('csharpcor', []);
Create Angular Controller for initiating the value.
- app.controller('NgCtrl', function($scope) {
- $scope.TextValues=123456789;
- });
Module and Controller name must assign to the HTML element.
- <html ng-app="'csharpcor'" ng-controller="NgCtrl">
Create Angular directives as given below.
- app.directive('numericonly', function () {
- return {
- require: 'ngModel',
- link: function (scope, element, attr, ngModelCtrl) {
- function fromUser(text) {
- var transformedInput = text.replace(/[^0-9]/g, '');
- if (transformedInput !== text) {
- ngModelCtrl.$setViewValue(transformedInput);
- ngModelCtrl.$render();
- }
- return transformedInput;
- }
- ngModelCtrl.$parsers.push(fromUser);
- }
- };
- });
Assgin a directive to the input text.
- <input type="text"
- numericonly
- class="form-control"
- ng-model="TextValues" />
Output