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

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


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>'  };});