2

I want to make Angular's number filter to have one and the same format no matter the chosen localization.

So, from the Angular source in GitHub I saw that the implementation of the filter looks like this:

function numberFilter($locale) {
   var formats = $locale.NUMBER_FORMATS;
   return function(number, fractionSize) {

       // if null or undefined pass it through
       return (number == null)
           ? number
           : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
                   fractionSize);
    };
}

I want my numbers to look like this: 123 456.78. Meaning,

formats.GROUP_SEP = " "; // Always, disrespect locale
formats.DECIMAL_SEP = "."; // Always, disrespect locale

I saw this post about overriding existing filters, but I can't figure out how to use it in my case to achieve exactly what I want.

Community
  • 1
  • 1
Yulian
  • 6,262
  • 10
  • 65
  • 92

2 Answers2

7

You can override $locale to use your own values like this:

var app = angular.module("test", []);

app.run(["$locale", function ($locale) {
    $locale.NUMBER_FORMATS.GROUP_SEP = " ";
    $locale.NUMBER_FORMATS.DECIMAL_SEP = ".";
}]);

Plnkr link: https://plnkr.co/edit/DlacehjcZrFRmWNFs1qZ?p=preview

Community
  • 1
  • 1
henrikmerlander
  • 1,554
  • 13
  • 20
  • 1
    Wow, that's a nice solution, but it doesn't work for me because I'm changing the localization dynamically with https://github.com/lgalfaso/angular-dynamic-locale. Any idea how to make this two things work together? – Yulian Mar 18 '16 at 13:05
  • 2
    Listen for an event emitted when locale change ? So you can force those values each time the locale change. – Walfrat Mar 18 '16 at 13:09
0

You can override it like this :

myApp.config(['$provide', function($provide) {
   $provide.decorator('numberFilter', ['$delegate', function($delegate) {

       return function(number, fractionSize) {

           // if null or undefined pass it through
           return (number == null)
           ? number
              : formatNumber(number, formats.PATTERNS[0], ' ', '.', fractionSize);
      };
    }
   }])
 }])

Another way would be to setup $locale.NUMBER_FORMATS to always have the value you wants.

Walfrat
  • 5,363
  • 1
  • 16
  • 35
  • It does not work because formatNumber is a "private" function. angular.js:12450 ReferenceError: formatNumber is not defined – Yulian Mar 18 '16 at 13:04
  • ah, then you have either to rewrite your own function or copy past all the private needed functions – Walfrat Mar 18 '16 at 13:08
  • then just write your own format number function or search for a tool on the net that does the job for you, that shouldn't be hard. – Walfrat Mar 18 '16 at 15:42