我有一个只应接受数字的字段,我通常知道input type="number"
。角度的最佳方法是什么,只允许数字?
答案 0 :(得分:1)
您可以创建一个类似于下面的指令,然后在HTML元素中将其用作属性
.directive('validNumber', function () {
return {
restrict: 'A',
require: '?ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
//8:"BACKSPACE",9:"TAB",17:"CTRL",18:"ALT",37:"LEFT",
//38:"UP",39:"RIGHT",40:"DOWN",45:"INSERT",46:"DELETE",
//48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9", 67:"C",86:"V",
//96:"0",97:"1",98:"2",99:"3",100:"4",101:"5",102:"6",103:"7",104:"8",105:"9",
//109:"-",110:".",144:"NUMLOCK", 189:"-",190:".",
var keyCode = [8, 9, 17, 37, 38, 39, 40, 45, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 67, 86, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 109, 110, 144, 189, 190];
element.bind("keydown", function (event) {
if ($.inArray(event.which, keyCode) == -1) {
scope.$apply(function () {
scope.$eval(attrs.validNumber);
event.preventDefault();
});
event.preventDefault();
}
});
}
};
});
答案 1 :(得分:0)
可能你可以使用这个简单的指令..
// ---Directive for Digit restriction on input fields.---------
myApp.directive('numbersOnly', function() {
return {
require : 'ngModel',
link : function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
// if the input is 'undefined'
if (inputValue == undefined)
return ''
var transformedInput = inputValue.replace(/[^0-9]/g, '');
if (transformedInput != inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
在HTML中,您可以将指令声明为
<input type="numbers" numbers-only ng-model="numberModel">
因此,理想情况下,此输入字段将使用数字作为唯一数据来更新模型..
这里发生的事情是,每次按下一个角色时,我们的指令 numbersOnly 都会对其进行监控,而这里只选择数字作为输入。
希望这有助于...... 干杯