如何限制输入为只接受数字? [英] How do I restrict an input to only accept numbers?
问题描述
我在AngularJS使用ngChange触发自定义函数,将删除用户添加到输入任何字母。
I am using ngChange in AngularJS to trigger a custom function that will remove any letters the user adds to the input.
<input type="text" name="inputName" data-ng-change="numbersOnly()"/>
问题是,我需要针对触发输入 numbersOnly()
,这样我可以删除输入的字母。我找了漫长而艰难的在谷歌和无法找到有关的事。
The problem is that I need to target the input that triggered numbersOnly()
so that I can remove the letters entered. I have looked long and hard on Google and was unable to find anything regarding this.
我该怎么办?
推荐答案
轻松的方式,使用的类型=数字它是否适合你的使用情况:
Easy way, use type="number" if it works for your use case:
<input type="number" ng-model="myText" name="inputName">
另一个简单的方法:
也可用于定义一个正则表达式,将限制所允许在现场纳克图案。另请参见食谱页有关表单的。
Another easy way: ng-pattern can also be used to define a regex that will limit what is allowed in the field. See also the "cookbook" page about forms.
的hackish?方法,$看NG-模型控制器:
Hackish? way, $watch the ng-model in your controller:
<input type="text" ng-model="myText" name="inputName">
控制器:
$scope.$watch('myText', function() {
// put numbersOnly() logic here, e.g.:
if ($scope.myText ... regex to look for ... ) {
// strip out the non-numbers
}
})
最好的办法后,使用一个指令一个$解析器。
我不会重复由@ pkozlowski.opensource提供的已经很好的答案,所以这里的链接: http://stackoverflow.com / A /二十一万五千九百四十五分之一千四百四十二万五千零二十二
Best way, use a $parser in a directive. I'm not going to repeat the already good answer provided by @pkozlowski.opensource, so here's the link: http://stackoverflow.com/a/14425022/215945
以上所有的解决方案包括使用NG-模式,这使得寻找这个
不必要的。
All of the above solutions involve using ng-model, which make finding this
unnecessary.
使用纳克变化会引起问题。见<一href=\"http://stackoverflow.com/questions/12176925/angularjs-reset-of-scope-value-doesnt-change-value-in-template-random-behav\">AngularJS - $ scope.value复位不会改变模板值(随机行为)
Using ng-change will cause problems. See AngularJS - reset of $scope.value doesn't change value in template (random behavior)
这篇关于如何限制输入为只接受数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!