angular-numeraljs.js 1.78 KB
Newer Older
eddie.woo's avatar
eddie.woo committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
/**
 * AngularJS filter for Numeral.js: number formatting as a filter
 * @version v2.0.1 - 2017-05-06
 * @link https://github.com/baumandm/angular-numeraljs
 * @author Dave Bauman <baumandm@gmail.com>
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */
'use strict';

(function (root, factory) {
  if (typeof exports === 'object') {
    // CommonJS
    module.exports = factory(require('numeral'));
  } else if (typeof define === 'function' && define.amd) {
    // AMD
    define(['numeral'], function (numeral) {
      return (root.ngNumeraljs = factory(numeral));
    });
  } else {
    // Global Variables
    root.ngNumeraljs = factory(root.numeral);
  }
}(this, function (numeral) {
  return angular.module('ngNumeraljs', [])
    .provider('$numeraljsConfig', function () {
      var formats = {};

      this.defaultFormat = function (format) {
        numeral.defaultFormat(format);
      };

      this.locale = function (locale) {
        numeral.locale(locale);
      };

      this.namedFormat = function (name, format) {
        formats[name] = format;
      };

      this.register = function (type, name, def) {
        numeral.register(type, name, def);
      };

      this.$get = function () {
        return {
          customFormat: function (name) {
            return formats[name] || name;
          },
          defaultFormat: this.defaultFormat,
          locale: this.locale,
          register: this.register,
          namedFormat: this.namedFormat
        };
      };
    })
    .filter('numeraljs', ['$numeraljsConfig', function ($numeraljsConfig) {
      return function (input, format) {
        if (input == null) {
          return input;
        }

        format = $numeraljsConfig.customFormat(format);

        return numeral(input).format(format);
      };
    }]);
}));