Skip to content

$formatters & $parsers in ngModelController

2015-04-19 21:46:36

Very often your rest api return date in timestamp format. Of course you have to display this value in "user friend" format. In normal way, to display this value you will use date filter.

{{dayOfBirth  | date:'yyyy-MM-dd'}}

but what about input ? here you can find answer

angular.module('app', [])

    .directive('btbwTimestampModel', function () {
        return {
            restrict: 'EA',
            require: 'ngModel',
            replace: true,
            link: function (scope, element, attrs, ngModelCtrl) {

                ngModelCtrl.$formatters.push(function (modelValue) {
                    return new Date(modelValue);

                ngModelCtrl.$parsers.push(function (viewValue) {
                    return new Date(viewValue).getTime();


How to use

<div class='"row"' ng-init='"someDate=1450828800000"'>
<div class='"col-xs-6"'><input btbw-timestamp-model="" class='"form-control"' ng-model='"someDate"' type='"date"'/></div>
<div class='"col-xs-3"'><pre>{{someDate}}</pre></div>
<div class='"col-xs-3"'><pre>{{someDate | date:'yyyy-MM-dd'}}</pre></div>