Using angularjs filter in input element

leon picture leon · Mar 11, 2013 · Viewed 90.5k times · Source

I hope I haven't missed anything obvious in the doco, if I have I'm sure someone will help.

I'm using asp.net webapi to return a DTO, with date fields. These are serialized using JSON.Net (in format '2013-03-11T12:37:38.693').

I'd like to use a filter but in an INPUT element, is this possible or should I create a new filter or directive to accomplish this?

// this just displays the text value
<input ui-datetime type="text" data-ng-model="entity.date" /> 
// this doesn't work at all
<input ui-datetime type="text" data-ng-model="{{entity.date|date:'dd/MM/yyyy HH:mm:ss a'}}" /> 
// this works fine
{{entity.date|date:'dd/MM/yyyy HH:mm:ss a'}}

Is there any shortcut I'm missing?

Answer

holographic-principle picture holographic-principle · Mar 11, 2013

In short: if you want your data to have a different representation in the view and in the model, you will need a directive, which you can think of as a two-way filter.

Your directive would look something like

angular.module('myApp').directive('myDirective', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModelController) {
      ngModelController.$parsers.push(function(data) {
        //convert data from view format to model format
        return data; //converted
      });

      ngModelController.$formatters.push(function(data) {
        //convert data from model format to view format
        return data; //converted
      });
    }
  }
});

HTML:

<input my-directive type="text" data-ng-model="entity.date" /> 

Here is a working jsFiddle example.