Angular: Numbers Only Directive

A directive to limit an input field to numbers and specific special characters only.

by Nalin Sajwan

HTML

<script src="http://code.angularjs.org/angular-1.0.0.js"></script>
<div ng-app="myApp">
	<h2>Validate Number</h2>
	<div ng-controller="MyCtrl">
	    <input type="text" ng-model="number" required="required" numbers-only />
	</div>
</div>

JavaScript

angular.module('myApp', []).directive('numbersOnly', function(){
   return {
     require: 'ngModel',
     link: function(scope, element, attrs, modelCtrl) {
       modelCtrl.$parsers.push(function (inputValue) {
           // this next if is necessary when using ng-required on your html input tag. 
           // In such cases, when a letter is typed first, this parser will be called
           // again, and the 2nd time, the value will be undefined
           if (inputValue == undefined) return '' 
           var transformedInput = inputValue.replace(/[^0-9]/g, '');
           if (transformedInput!=inputValue) {
              modelCtrl.$setViewValue(transformedInput);
              modelCtrl.$render();
           }         

           return transformedInput;         
       });
     }
   };
});

function MyCtrl($scope) {
    $scope.number = ''
}