【发布时间】:2016-05-31 09:31:03
【问题描述】:
我只想在我的 Angular JS 应用程序中将文本框设为数字。 这是我的代码- 脚本.js
app.directive('numbersonly', function () {
return {
restrict: 'A',
link: function (scope, elm, attrs, ctrl) {
elm.on('keydown', function (event) {
if (event.which == 64 || event.which == 16) {
// to allow numbers
return false;
} else if (event.which >= 48 && event.which <= 57) {
// to allow numbers
return true;
} else if (event.which >= 96 && event.which <= 105) {
// to allow numpad number
return true;
} else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) {
// to allow backspace, enter, escape, arrows
return true;
} else {
event.preventDefault();
// to stop others
return false;
}
});
}
}
});
在 UI 上-
<input type="text" id="txtEmpAge" data-ng-model="newemployee.Age" class="form-control" numbersonly required />
但文本框同时接受数字和字符。
【问题讨论】:
-
在控制器中使用正则表达式并查看 ngPattern
-
如果它只有一个输入并且您不需要它作为指令,您可以使用答案here
标签: angularjs