Radek Anuszewski
Radek Anuszewski

Reputation: 1910

Is it possible to add additional zeros with AngularJS $formatters? (or in any possible way, with number input?)

I want to write AngularJS directive which adds zeros to number in input, even if they are not necessary. I have:

<input type="number" step="0.1">

And even it has value 1, I want to display it as 1.0. And of course if step is 0.01, it should always be displayed as 1.00. Crux of the matter is that, if it is possible, I want to use number input instead of text (built-in HTML validation, mobile devices keyboard etc..). So I thought about AngularJS formatters (simple example to just do it for hard-coded values):

ngModel.$formatters.push(function(value) {
    return Number((value + 0.00001).toFixed(3));
});

And it didn't work, it lost unnecessary zeros. And, because input has type number, I can not return String from formatter. I have made a plunk with my try: Plunker: Directive which adds additional zeros. T think it should be possible in some way (maybe without Angular?), because if I have hard-coded:

<input type="number" value="3.000">

It displays 3.000 in input. Even if I open Developer Console on my Plunk I am able to do this:

document.querySelector('#with-directive').value = '33.0'

And it displays 33.0 (DOM manipulation is of course a solution to solve this problem, but I think it can lead to code, which is not easy to maintain and I want to avoid it if possible) Am I right, is it possible to do it? I would be very grateful if anybody decides to help me, thank you in advance.

Upvotes: 0

Views: 60

Answers (1)

Simon Sch&#252;pbach
Simon Sch&#252;pbach

Reputation: 2683

I suggest to use type tel instead of number. Because ios doesn't support type number and on the other side if you use type tel then your output is a string. You have to adust your $formatter like that.

ngModel.$formatters.push(function(value) {
    return (parseInt(value)).toFixed(3);
 });

Upvotes: 1

Related Questions