Formatting time inputs nicely with AngularJS

Unfortunately the AngularJS code uses a fixed formatter for the time when a browser doesn’t support the time input natively (eg firefox). The code specifies ‘HH:mm:ss.sss’ which is pretty pointless for most users I would imagine (I’m building a calendering app). Fortunately we can hook into this formatter and fix it, although the ideal would be to override it unfortunately there are local variables that we can’t override particularly easily. So I took the easy route of just modifying the string after it had already been parsed:

/* Attach to input time elements and switch their formatting to be HH:MM
 */             
angularApp.directive('ngModel', function( $filter ) {
    return {
        require: '?ngModel',
        link: function(scope, elem, attr, ngModel) {
            if( !ngModel )
                return;
            if( attr.type !== 'time' )
                return;
                    
            ngModel.$formatters.unshift(function(value) {
                return value.replace(/:00\.000$/, '')
            });
        }
    }   
});         

6 thoughts on “Formatting time inputs nicely with AngularJS”

    1. Thanks! All my values were 0’s anyway so isn’t an issue for me. By the way within []’s you dont need to escape dots etc so you could write regex as :\d{2}[.,]\d{3}$

  1. Thanks a lot for this… After spending an entire day trying to solve this problem, I came to realize that this was a limitation/bug/”feature” introduced in >1.2 versions. Worked on latest Firefox with v1.03 (http://jsfiddle.net/yk29zeLz/1/)

    However, with latest Firefox, and angularjs 1.6.7, the regular expression “\d{2}[.,]\d{3}$” didn’t work for me. Having spend more than enough time on this already I did not pursue it further and used “/:00\.000$/” instead.

    Many thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *