Numbers only directive using $parsers
HTML
<script src="https://code.angularjs.org/1.3.1/angular.js"></script>
<body ng-app="onlyDigitsApp">Only numbers allowed:
<input type="text" ng-model="someModel" only-digits />
</body>
JavaScript
angular.module('onlyDigitsApp', [])
.directive('onlyDigits', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
// The 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;
});
}
};
})