Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with transformed data in AngularJS

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

like image 769
itarato Avatar asked Feb 14 '26 00:02

itarato


1 Answers

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.

like image 100
Caio Cunha Avatar answered Feb 15 '26 13:02

Caio Cunha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!