AngularJS - Formatting ng-model before template is rendered in custom directive

Lulu picture Lulu · Apr 9, 2013 · Viewed 10.5k times · Source

I am creating a custom directive in Angular JS. And I want to format the ng-model before the template renders.

This is what I have so far:

app.js

app.directive('editInPlace', function() {
    return {
        require: 'ngModel',
        restrict: 'E',
        scope: { ngModel: '=' },
        template: '<input type="text" ng-model="ngModel" my-date-picker disabled>'
    };
});

html

<edit-in-place ng-model="unformattedDate"></edit-in-place>

I want to format the unformattedDate value before it is entered in the ngModel of the template. Something like this:

template: '<input type="text" ng-model="formatDate(ngModel)" my-date-picker disabled>'

but that gives me an error. How to do this?

Answer

Caio Cunha picture Caio Cunha · Apr 9, 2013

ngModel exposes its controller ngModelController API and offers you a way to do so.

In your directive, you can add $formatters that do exactly what you need and $parsers, that do the other way around (parse the value before it goes to the model).

This is how you should go:

app.directive('editInPlace', function($filter) {
  var dateFilter = $filter('dateFormat');

  return {
    require: 'ngModel',
    restrict: 'E',
    scope: { ngModel: '=' },
    link: function(scope, element, attr, ngModelController) {
      ngModelController.$formatters.unshift(function(valueFromModel) {
        // what you return here will be passed to the text field
        return dateFilter(valueFromModel);
      });

      ngModelController.$parsers.push(function(valueFromInput) {
        // put the inverse logic, to transform formatted data into model data
        // what you return here, will be stored in the $scope
        return ...;
      });
    },
    template: '<input type="text" ng-model="ngModel" my-date-picker disabled>'
  };
});