Let’s keep the example simple so that it can be run directly in a browser. The my-number-filter.js is a custom AngularJS filter and has two parameters (minPrecision and maxPrecision), which allow the filter’s consumer to set the desired minimum and maximum decimal precision.
The filter injects a custom service, precision-service.js, that simply determines where the decimal place is on the inputted value.
In the following test1.html example, we have set those values to 2 and 4, respectively, so that any numeric value will be displayed with a minimum of 2 decimal places and a maximum of 4 decimal places. Inputted values of 10.2 or 10.200000 will be display as 10.20. In a real scenario, the value would not be hard-coded, but would be coming from a view model. The test1.html simply employs the my-number-filter to format the two number values as described above. By running test1.html you can see the result.
Now let’s try another example where we can reuse my-number-filter in a directive to get the same effect in an HTML input element. We will add another filter: my-number-sanitizer-filter.js to sanitize the value to strip away any non-numeric characters and comma separators. The directive allows for adding characters to append to the resulting value such as a $ or a % for currency or percentages.
The directive my-numeric-input-directive.js uses my-number-filter in the directive’s link function when the model is updated upon loading the page and when focus leaves the input. The directive my-numeric-input-directive.js uses my-number-sanitizer-filter.js when the input receives focus and as the user keys values. This keeps the model value clean as the user types, but then formats the display when the user removes focus from the input.
The test2.html has an input that allows you to enter in values and a label to display how the formatted value will appear once the user moves focus away from the input.
View the HTML in the browser. As you type, notice the display in the label under the input will add commas to account for thousands, millions, etc. The input will also prevent any more than 4 decimals to be entered and will remove extraneous zeros after the decimal (e.g. 10.2000) when focus leaves the control.
This concludes the simple example of using a directive and filters to handle custom number formats. The beauty of AngularJS directives is their ability to be customized to your liking. Once built, they can be reused throughout your applications. Hopefully you find this simple example helpful.
Consider adding a CTA to learn more about this topic.