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

4

1 回答 1

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.

于 2013-03-30T13:10:07.120 回答