Handle Number Inputs With AngularJS

AngularJS Jan 24, 2019

A quick post to share my knowledge about handling number inputs on forms properly on different browsers. I faced this issue while working on one of my projects wherein Safari and Chrome handle number inputs very differently thus making things complex sometimes.

To support above statement, I am using below code and attaching screenshots to show behaviour of different browsers.

Code

<input type="number" placeholder="Enter Number"/>

Screenshots

Important thing to note here is that Safari allows characters along with numbers whereas Chrome only allow numbers. This make things difficult sometimes when you need to handle some scenarios or validations.

To overcome it, There was a way suggested on some forums to use directives on input text field instead of input number which will handle all possible scenarios.

I extended the suggested solution to my needs and posting it here . It does not only handle numbers on text fields but also handle some basic scenarios like:

  1. Maximum lenth of number same as max-length attribute of html
  2. Allow decimals or not on input
  3. Set decimal places explicitly

Full Code:

Hope this helps. Happy Coding!

Related Tags:

AngularJS   JavaScript   Utilities   Angular1