AngularJS 带条件的日期过滤器

AngularJS date filter with condition

我使用 ng-bind 和日期过滤器来输出日期的时间。

<span ng-bind="ctrl.model.myDate | date:'HH:mm'"><span>

现在我希望能够使用此过滤器在 12 小时格式和 24 小时格式之间切换输出:日期:'HH:mm' 和日期:'hh:mm'

因此我有一个 属性:

model.is24h= true

如何在 ng-bind 表达式中插入一个条件来评估我的 属性 以 12 小时或 24 小时格式输出?

类似于:

<span ng-bind="ctrl.model.myDate | {{ctrl.model.is24h: date:'HH:mm' || date:'hh:mm'}}"><span>

您可以在指令参数中使用三元运算符:

<span ng-bind="ctr.model.myDate | date:(ctrl.model.is24h?'HH':'hh')+':mm'"><span>

尝试更改此条件的过滤器代码。

angular.module('yourmodule').filter('date', function ($filter, $scope) {
            return function (input) {
                if (input == null) { return ""; }
                if ($scope.is24h) {
                    return $filter('date')(new Date(input), 'HH:mm').toUpperCase();
                }

                return $filter('date')(new Date(input), 'hh:mm').toUpperCase();
            };
        });

html 应该是

<span ng-bind="ctrl.model.myDate | date"><span>

只需添加一个以变量作为参数的新过滤器

http://jsfiddle.net/HB7LU/13224/

HTML

<span ng-bind="myDate | newDate:is24h"></span>
<button type="button" ng-click="is24h = !is24h">Swap</button>

JS

myApp.filter('newDate', function ($filter) {
    return function (input, arg) {
        var hFormat = arg ? 'HH' : 'hh';
        return $filter('date')(new Date(input), hFormat  + '.mm');
    };
});