My project has a form with around 16 text fields. The input needs to be numeric, and different fields will have different min/max values. I was able to find the following jsfiddle (http://jsfiddle.net/thomporter/DwKZh/) and adapt the parsing to the following (http://jsfiddle.net/WdBju/):
angular.module('myApp', []).directive('numbersOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
if (inputValue == undefined) {
return '';
}
var firstParse = inputValue.replace(/[^0-9 . -]/g, '');
var safeParse = firstParse.charAt(0);
var prepParse = firstParse.substring(1,firstParse.length);
var secondParse = safeParse + prepParse.replace(/[^0-9 .]/g, '');
var n = secondParse.indexOf(".");
var transformedInput;
if (n == -1) {
transformedInput = secondParse;
}
else {
safeParse = secondParse.substring(0,n+1);
firstParse = (secondParse.substring(n+1,secondParse.length)).replace(/[^0-9]/g, '');
n = 2;
if (firstParse.length <= n) {
transformedInput = safeParse + firstParse;
}
else {
transformedInput = safeParse + firstParse.substring(0,n);
}
}
var min = -25;
var max = 25;
if (transformedInput!=inputValue ||
transformedInput < min ||
transformedInput > max) {
var returnValue;
if (transformedInput < min || transformedInput > max) {
returnValue = transformedInput.substring(0,transformedInput.length-1);
}
else {
returnValue=transformedInput;
}
modelCtrl.$setViewValue(returnValue);
modelCtrl.$render();
}
return returnValue;
});
}
};
});
I am happy with the parsing, but the min/max and precision values are hard-coded in. Should I leave this as a directive and pass variables? Or would a function be more appropriate?
input type=number
. No directive needed. – Jason Oct 1 '13 at 18:49