How do I restrict an input to only accept numbers?
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+$/;
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)