Issue
I need a directive which will parse user input to date and validate it. So I wrote the following:
myDirectives.directive('myDate', function($filter) {
'use strict';
return {
require:'ngModel',
restrict:'A',
link:function (scope, elem, attrs, ctrl) {
var dateFormat = attrs.myDate ? attrs.myDate : 'shortDate';
ctrl.$formatters.unshift(function(modelValue) {
return $filter('date')(modelValue, dateFormat);
});
ctrl.$parsers.unshift(function(viewValue) {
var date = new Date(viewValue);
if (isNaN(date)) {
ctrl.$setValidity('date', false);
return undefined;
} else {
var dateString = $filter('date')(date, dateFormat);
if (dateString !== viewValue) {
ctrl.$setViewValue(dateString);
}
ctrl.$setValidity('date', true);
return date;
}
});
}
};
});
Parsing need to occur only after when input loses focus, so I use another directive, which I found here. The problem is
ctrl.$setViewValue(dateString);
won't work, because as indicated in angularjs documentation, setViewValue() must be called from within a DOM event handler. What should I do to reflect back parsing result?
Solution
Instead of
ctrl.$setViewValue(dateString);
I needed to write
elem.val(dateString);
and the problem was solved. So, my directive now looks like below:
myDirectives.directive('myDate', function ($filter) {
'use strict';
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, elem, attrs, ctrl) {
var dateFormat = attrs.myDate ? attrs.myDate : 'shortDate';
ctrl.$formatters.unshift(function (modelValue) {
return (modelValue) ? $filter('date')(modelValue, dateFormat) : '';
});
ctrl.$parsers.unshift(function (viewValue) {
var date = new Date(viewValue);
if (isNaN(date)) {
ctrl.$setValidity('date', false);
return undefined;
} else {
var dateString = $filter('date')(date, dateFormat);
if (dateString !== viewValue) {
elem.val(dateString);
}
ctrl.$setValidity('date', true);
return date;
}
});
elem.unbind('input').unbind('keydown').unbind('change');
elem.bind('blur', function () {
scope.$apply(function () {
ctrl.$setViewValue(elem.val()); //this method name is misleading;
//it actually sets model value?!
});
});
}
};
});
Note, that I incorporated the code from another directive which was responsible for pushing view value to model, when focus is lost.
Answered By - synergetic
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.