3

I have a list of timestamps. I can list them with AngularJS. However I want to list it as date strings. Those date strings should be editable - and when it's finished I would like to have the related timestamp updated too.

My first question is: what is the AngularJS way of presenting items in a different format (filters?) and still have the bidirectional data binding? (Module, directive, listeners?)

Thank you

itarato
  • 795
  • 1
  • 8
  • 24
  • Why don't you just create a `Date` object from the timestamp and get the timestamp back when you need it with `.getTime()`? `var d = new Date(timestamp); console.log(d); console.log(d.getTime());` – maxdec Mar 30 '13 at 11:56
  • some solutions here http://stackoverflow.com/questions/14474555/how-to-format-a-date-using-ng-model – charlietfl Mar 30 '13 at 13:06

1 Answers1

7

If your editable data is the raw data (Timestamp), than you shall go with filters.

But if you want it to be editable in date string format, than you'll need to create a directive to augment the ngModel+input, by adding custom $parsers and $formatters.

It's quite simple indeed:

app.directive('dateFormat', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attr, ngModelCtrl) {
      ngModelCtrl.$formatters.unshift(function(valueFromModel) {
        // return how data will be shown in input
      });

      ngModelCtrl.$parsers.push(function(valueFromInput) {
        // return how data should be stored in model
      });
    }
  };
});

In your HTML:

<input type="text" ng-model="date" date-format />

The directive will require ngModelController so you can augment its behavior.

Made a Plunker. Of course, if you need simple date manipulation, consider using Filters programmatically inside your directive, so you don't repeat already implemented filters. I'm using it in Plunker, so you can see how to use.

Caio Cunha
  • 23,326
  • 6
  • 78
  • 74