I defined a directive like this:
angular.module('MyModule', []) .directive('datePicker', function($filter) { return { require: 'ngModel', link: function(scope, elem, attrs, ctrl) { ctrl.$formatters.unshift(function(modelValue) { console.log('formatting',modelValue,scope,elem,attrs,ctrl); return $filter('date')(modelValue, 'MM/dd/yyyy'); }); ctrl.$parsers.unshift(function(viewValue) { console.log('parsing',viewValue); var date = new Date(viewValue); return isNaN(date) ? '' : date; }); } } });
The parser seems to fire every time I type a key in my text box, but what is the default event, is it keyup or input ? And how do I change it to only fire onchange ? In fact, there is no need to shoot more often than that.
In addition, I actually manipulate the contents of this input using the jQuery UI datepicker. When you click on a calendar, it does not seem to trigger a corresponding event that causes the model to update / the parser starts. I think I can make the event fire , but I need to know which one.
Trying to use scope.$apply() , but this does not help:
.directive('datepicker', function($filter) { return { require: 'ngModel', link: function(scope, elem, attrs, ctrl) { $(elem).datepicker({ onSelect: function(dateText, inst) { console.log(dateText, inst); scope.$apply(); } }); ctrl.$formatters.unshift(function(modelValue) { console.log('formatting',modelValue); return $filter('date')(modelValue, attrs.datePicker || 'MM/dd/yyyy'); }); ctrl.$parsers.unshift(function(viewValue) { console.log('parsing',viewValue); return new Date(viewValue); }); } } })
I donβt think that the solution given here works for me, because (a) I want to use the value of the datepicker attribute to select the date format or other parameters, but more importantly, (b) it seems that it returns the string to the model when I you need an actual date object ... so you need to do some form of parsing and apply to ng-model .