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()"/>
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.
What can I do?
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? way, $watch the ng-model in your controller:
<input type="text" ng-model="myText" name="inputName">
Controller:
$scope.$watch('myText', function() { // put numbersOnly() logic here, e.g.: if ($scope.myText ... regex to look for ... ) { // strip out the non-numbers } })
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.com/a/14425022/215945
All of the above solutions involve using ng-model, which make finding this
unnecessary.
Using ng-change will cause problems. See AngularJS - reset of $scope.value doesn't change value in template (random behavior)
Using ng-pattern
on the text field:
<input type="text" ng-model="myText" name="inputName" ng-pattern="onlyNumbers">
Then include this on your controller
$scope.onlyNumbers = /^\d+$/;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With