Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have AngularJS internationalize numeric inputs?

We're trying to have AngularJS internationalize <input type='number' /> values.

We've included the localization file (e.g. angular-locale_it-it.js), but the values are still displayed using the English locale.

This is a problem because our back-end (and management) expects numeric values to be in the user's locale, and receiving 123.45 instead of 123,45 causes an error.

You can find an example on jsFiddle.

It works in Chrome 27

Screenshot of the result in Chrome

but it's not working in Firefox 21 and Internet Explorer 10.

Screenshot of the result in Firefox

like image 759
Albireo Avatar asked Jun 21 '13 15:06

Albireo


2 Answers

This may not be the answer you want, but maybe it helps you a little bit:

JsBin: http://jsbin.com/iyulaj/1/

Using a directive you can take the data of the input, parse it and then put it to the $scope variable. Please see: http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController ($parsers and $formatters. I took it from: Using angularjs filter in input element).

The directive could search for a comma and replace it with a dot. It could look like this:

angular.module('MyModule').directive('numberinput', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelController) {

            ngModelController.$parsers.push(function(data) {
                //convert data from view format to model format
                return data.replace(',', "."); //converted
            });

            ngModelController.$formatters.push(function(data) {
                //convert data from model format to view format
                return data.replace('.', ","); //converted
            });

            // http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController

        }
    };
});

The input field:

<input ng-model='value' type='text' numberinput='' />

Also note that the input is now a text field. Have a look at this: http://jsbin.com/iyurol/1/

The input is a number field. But type 11,5 and it will output ùndefined (note that I live in Germany and we're using the comma-notation). So the browser doesn't 'parse' the number correctly if it's not in dot-notation, even if you live in regions with comma-notation...

Please correct me, if there's something wrong about that ;)

like image 133
AndreM96 Avatar answered Oct 14 '22 01:10

AndreM96


It could be not related to angular. IMHO that should be provided by the browser. It should be driven by the lang attribute:

<!DOCTYPE html>
<html lang="it">
...

See more details at HTML5 number inputs – Comma and period as decimal marks

like image 26
Plap Avatar answered Oct 14 '22 03:10

Plap