Search code examples
javascriptangularjsmomentjsangular-moment

Global Variables in Angular


I've got some date ISO strings that I want to format into human-readable dates. I'm using the angular-moment library to format these dates inside my template using a filter.

<span>{{ $ctrl.date | amCalendar:referenceTime:formats }}</span>

I want to customise the format of the date displayed to the following:

const dateFormats = {
  relative: {
    sameDay: '[Today at] LT',
    lastWeek: 'DD MMM, YYYY [at] LT',
    sameElse: 'DD MMM, YYYY [at] LT'
  }
}

So I can do this in my template:

<span>{{ $ctrl.date | amCalendar:null:dateFormats }}</span>

However, I want those dateFormats to live somewhere globally instead of exclusively inside this component's controller, as I'd like to be able to reference these dateFormats in other templates down the line.

Would this qualify as proper use-case to attach dateFormats to $scope or is there a better way to handle this?

Any help is appreciated. Thanks in advance!


Solution

  • You should create a custom filter of your own. Something like this:

    angular
      .module('myApp')
      .filter('myDateFormat', ['$filter',function ($filter) {
          const dateFormats = {
            relative: {
              sameDay: '[Today at] LT',
              lastWeek: 'DD MMM, YYYY [at] LT',
              sameElse: 'DD MMM, YYYY [at] LT'
            } 
          }
          return function() {
            return $filter('amCalendar')(null, dateFormats)
          }
      }]);
    

    Now, you can easily utilize this filter from any template in your module:

    <span>{{ $ctrl.date | myDateFormat }}</span>