Search code examples
javascriptangularjsangular-filters

How can I override Angular's number filter?


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.


Solution

  • 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