我的项目有一个包含大约 16 个文本字段的表单。输入需要是数字,不同的字段会有不同的最小值/最大值。我能够找到以下 jsfiddle ( http://jsfiddle.net/thomporter/DwKZh/ ) 并将解析调整为以下 ( 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;
});
}
};
});
我对解析很满意,但是最小/最大和精度值是硬编码的。我应该把它作为指令保留并传递变量吗?还是一个函数更合适?