2

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>

3 Answers 3

7

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');
    };
});
Sign up to request clarification or add additional context in comments.

1 Comment

why do you add toUpperCase() inside the filter?
0

Try to change your filter code for this condition.

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 should be

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

Comments

-1

You can use trenary operator in directive parameter:

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

1 Comment

2 watchers for this use case seems not to be the right way for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.