问题
I have a number input on a page, and I want it restricted to whole number values, no decimals. I am using forms and angularjs for validation. What do I have to do to make decimals not allowed? I tried setting step to 1, but this changed nothing. Many other issues discuss getting browsers to support decimals - I seem to be having the opposite problem.
回答1:
You can make a custom directive for that, incorporating the ngModelController. Like this: Proof of Concept
module.directive("noDecimalInput", function() {
return {
restrict: "A",
require:"ngModel",
link: function(scope,element,attr,ctrl) {
ctrl.$parsers.push(function(value){
if(value.indexOf(".")>-1) {
ctrl.$setValidity("notDecimal",false);
return undefined;
}
ctrl.$setValidity("notDecimal",true);
return value;
});
}
}
});
来源:https://stackoverflow.com/questions/27042346/how-to-restrict-input-number-to-non-decimal