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="number" min="0" max="10" ng-model="number" required="required" ng-blur="onBlur(number);" maintain-number-min-max />
</div>
</div>
JavaScript
angular.module('myApp', []).directive('maintainNumberMinMax', function(){
return {
require: 'ngModel',
ngBlur: '&',
link: function(scope, element, attrs, modelCtrl) {
scope.onBlur = function(number){
console.log("===> ",typeof number);
if(isNaN(number)) {
var min = parseInt(attrs.min);
number = min;
console.log("On blur");
modelCtrl.$setViewValue(number);
modelCtrl.$render();
}
return number;
};
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
// console.log("attrs ==> ",attrs);
// console.log("inputValue ==> ",inputValue);
var min = parseInt(attrs.min);
var max;
if(typeof attrs.max !== "undefined") {
max = parseInt(attrs.max);
}
var valueChanged = false;
if(isNaN(inputValue) && inputValue < min) {
console.log("2. updating value to ==> ",min);
inputValue = min;
valueChanged = true;
} else if(typeof max !== "undefined" && inputValue > max) {
console.log("3. updating value to ==> ",max);
inputValue = max;
valueChanged = true;
}
if(valueChanged) {
modelCtrl.$setViewValue(inputValue);
modelCtrl.$render();
}
return inputValue;
});
}
};
});
function MyCtrl($scope) {
$scope.number = ''
}