Set an AngularJS date filter format to be used by all references to the date filter?

前端 未结 5 951
余生分开走
余生分开走 2021-02-18 18:03

Rather that having to define a custom format for each call to the date filter, is there a way to globally define a default format (other than \'medium\'

相关标签:
5条回答
  • 2021-02-18 18:19

    Use a decorator,

    It's not what you explicitly asked for, use a decorator. it's built in angular and designed to patch services, directives, filters etc ...

    in your case, if the date filter is not provided, you should use your custom date format.

    app.config(function ($provide) {
        $provide.decorator('dateFilter', function ($delegate) {
            return function () {
    
                // Check if the date format argument is not provided
                if (!arguments[1]) { 
                    arguments[1] = 'dd MMMM @ HH:mm:ss';
                }
    
                var value = $delegate.apply(null, arguments);
                return value;
            };
        })
    });
    
    0 讨论(0)
  • 2021-02-18 18:20

    Based on some more research and then considering the comment by moderndegree, I have found that the following myDate filter will work:

    .filter('myDate', function($filter) {    
        var angularDateFilter = $filter('date');
        return function(theDate) {
           return angularDateFilter(theDate, 'dd MMMM @ HH:mm:ss');
        }
    });
    
    0 讨论(0)
  • 2021-02-18 18:23

    In case you are working with .aspx pages and have the date format stored in a configuration file...

    1. From the .aspx that injects your Angular page, set a global variable with the web.config date format

      var _settingsDateFormat = '<%=appSettings.DateFormat%>';

    2. Set a global filter to be used through your app

    yourModule.filter('myDateFormat', function ($filter) {
            return function (input) {
                if (input == null) { return ""; }
                var formattedDate = $filter('date')(new Date(input), _settingsDateFormat);
                return formattedDate;
            };
    });
    1. Just add the custom filter to your dates
    
           Effective {{row.StartDate|myDateFormat}} - {{row.StopDate|myDateFormat}}
        
    0 讨论(0)
  • 2021-02-18 18:24

    Try this

    angular.module('yourmodule').filter('myDate', function($filter)
    {
        return function(input)
        {
            if(input == null){ return ""; }
            var _date = $filter('date')(new Date(input), 'dd MMMM @ HH:mm:ss');
            return _date.toUpperCase();
        };
    });
    

    Html

    {{systemTime | myDate}}
    

    Date filtering and formatting in Angular js.

    0 讨论(0)
  • 2021-02-18 18:33

    The format defaults to mediumDate if none is provided. There is nothing built in to have it default to something else.

    https://github.com/angular/angular.js/blob/master/src/ng/filter/filters.js#L382

    0 讨论(0)
提交回复
热议问题