问题描述
限时送ChatGPT账号..我在 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()
的输入,以便我可以删除输入的字母.我在 Google 上搜索了很长时间,但找不到任何关于此的信息.
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.
我能做什么?
推荐答案
简单方法,使用type="number" 如果它适用于您的用例:
Easy way, use type="number" if it works for your use case:
<input type="number" ng-model="myText" name="inputName">
另一种简单的方法:ng-pattern 也可用于定义限制允许的正则表达式在该领域.另请参阅关于表单的cookbook"页面.
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.
黑客?方式, $watch 控制器中的 ng-model:
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
}
})
最好的方法,在指令中使用 $parser.我不会重复@pkozlowski.opensource 提供的已经很好的答案,所以这里是链接:https://stackoverflow/a/14425022/215945
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: https://stackoverflow/a/14425022/215945
以上所有解决方案都涉及使用 ng-model,这使得查找 this
变得不必要.
All of the above solutions involve using ng-model, which make finding this
unnecessary.
使用 ng-change 会导致问题.请参阅 AngularJS - $scope 的重置.值不会改变模板中的值(随机行为)
Using ng-change will cause problems. See AngularJS - reset of $scope.value doesn't change value in template (random behavior)
这篇关于如何将输入限制为仅接受数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论