Search code examples
javascriptangularjsdatetimetimestampangular-ngmodel

Bind ng-model holding a timestamp to datetime-local input


I am trying to render a <input type="datetime-local> field with ng-model representing a timestamp:

<input type="datetime-local" ng-model="object.value">

with

$scope.object.value = 1433109600000;

Console shows [ngModel:datefmt] error.

How do I correctly bind $scope.object.value to the input field? (the timestamp comes from a webservice within an nestest object)

Some Plnkr: http://plnkr.co/edit/TGpKVNF1tv0b1h6JPBT8?p=preview


Solution

  • It must be date object:

    $scope.object = {
      name: 'Demo',
      value: new Date(1433109600000)
    }
    

    Updated demo

    Or create a directive:

    app.directive('bindTimestamp', function () {
      return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
          ngModel.$formatters.push(function (value) {
            return new Date(value);
          });
        }
      };
    });
    

    Directive demo