我正在制定一个要求,我只想在文本框或数字框(输入类型编号)中使用偶数.最小和最大限制,如4到14,如果我们有数字框,它应该只增加2步.
我尝试使用HTML输入类型编号,最小最大值和步骤属性它工作正常,但我们可以编辑任何数字的文本框,以限制我尝试使用指令,但它不适合我.如果有人能帮我解决这个问题,我将很高兴.
HTML:
脚本:
解决方法
@H_502_17@<form name="testForm">
<div ng-controller="MyCtrl">
<input type="text" name="testInput" ng-model="number" ng-min="2" ng-max="14" required="required" numbers-only="numbers-only" />
<div ng-show="testForm.testInput.$error.nonnumeric" style="color: red;">
Numeric input only.
</div>
<div ng-show="testForm.testInput.$error.belowminimum" style="color: red;">
Number is too small.
</div>
<div ng-show="testForm.testInput.$error.abovemaximum" style="color: red;">
Number is too big.
</div>
<div ng-show="testForm.testInput.$error.odd" style="color: red;">
Numeric is odd.
</div>
</div>
</form>
angular.module('myApp',[]).directive('numbersOnly',function () {
return {
require: 'ngModel',link: function (scope,element,attrs,modelCtrl) {
element.bind('blur',function () {
if (parseInt(element.val(),10) < attrs.ngMin) {
modelCtrl.$setValidity('belowminimum',false);
scope.$apply(function () {
element.val('');
});
}
});
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 || (parseInt(transformedInput,10) < parseInt(attrs.ngMin,10) && transformedInput !== '1') || parseInt(transformedInput,10) > parseInt(attrs.ngMax,10) || (transformedInput % 2 !== 0 && transformedInput !== '1')) {
if (transformedInput != inputValue) {
modelCtrl.$setValidity('nonnumeric',false);
} else {
modelCtrl.$setValidity('nonnumeric',true);
}
if (parseInt(transformedInput,10) && transformedInput !== '1') {
modelCtrl.$setValidity('belowminimum',false);
} else {
modelCtrl.$setValidity('belowminimum',10)) {
modelCtrl.$setValidity('abovemaximum',false);
} else {
modelCtrl.$setValidity('abovemaximum',true);
}
if (transformedInput % 2 !== 0 && transformedInput !== '1') {
modelCtrl.$setValidity('odd',false);
} else {
modelCtrl.$setValidity('odd',true);
}
transformedInput = '';
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
return transformedInput;
}
modelCtrl.$setValidity('nonnumeric',true);
modelCtrl.$setValidity('belowminimum',true);
modelCtrl.$setValidity('abovemaximum',true);
modelCtrl.$setValidity('odd',true);
return transformedInput;
});
}
};
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。