AngularJS makes it easy to add thousands separators when displaying numbers on a web page. All you need to use is the number
filter provided by the AngularJS framework. Here’s a quick example:
<span>{{company.employeeCount | number }}</span>
But there is not an easy way to add thousands separators to input boxes. The number
filter does not work on input boxes, so we can’t use it to help us. For example, the following markup does not work in AngularJS:
<!-- does not work -->
<input type="text" ng-model="company.employeeCount | number" />
So we’re left to create a custom directive to add commas for thousands separators in text boxes.
Before we start writing the directive, we need to step back and consider the user experience we want the directive to provide. We don’t always want to show the thousands separators in the text box. For instance, when the text box has focus and the user is editing the number, the thousand separators should not show. And when the user is done editing and the text box loses focus, we want to re-add the thousands separators.
To provide this user experience, I created the FCSA Number directive. All you need to do is add fcsa-number
as an attribute on the input text box, and the directive will take care of adding commas for thousands separators, and it will remove the commas when the text box receives focus.
Here’s a quick demo of the directive (It also provides optional number validations too)
If you want to use it on your site, just follow the installation instructions in the Readme file on the project’s Github site.