Angular: Numbers Only Directive

A directive to limit an input field to numbers only.

by Pankaj Parkar

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<div ng-controller="MyCtrl">
    <input type="text" ng-model="number" required="required" numbers-only="numbers-only" />
    <br>
    {{number}}
</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 for when using ng-required on your input. 
           // 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;         
       });
     }
   };
}).controller('MyCtrl',MyCtrl)
function MyCtrl($scope) {
    $scope.number = ''
};