Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 649
Lulu Avatar asked Apr 09 '13 12:04

Lulu


Video Answer


1 Answers

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>'
  };
});
like image 97
Caio Cunha Avatar answered Oct 18 '22 14:10

Caio Cunha