Search code examples
angularjsangular-filters

AngularJS date filter with condition


I use ng-bind and the date filter to output a time of a date.

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

Now I would like to be able to switch the output between 12 and 24h format, with this filter: date:'HH:mm' and date:'hh:mm'

Therefore I have a property:

model.is24h= true

How can I insert a condition into the ng-bind expression to evaluate my property to output in 12h or 24h format?

Something like:

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

Solution

  • Just add a new filter with the variable as an argument

    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');
        };
    });