I'm trying to wrap an <input>
in a directive so that I can handle date validation and convert it from a string to an actual Date
object and maintain the Date
version in the original scope. This interaction is working as expected. But the ng-pattern
on the <input>
element isn't acting right. It is never invalidating the <input>
, regardless of what is entered.
HTML
<pl-date date="date"></pl-date>
JS
.directive("plDate", function (dateFilter) {
return {
restrict: 'E',
replace: true,
template: '<input id="birthDateDir" name="birthDate" type="text" ng-pattern="{{getDatePattern()}}" ng-model="dateInput">',
scope: {
date: '='
},
link: function (scope) {
scope.dateInput = dateFilter(scope.date, 'MM/dd/yyyy');
scope.$watch('date', function (newVal) {
if (newVal !== scope.tmp) {
if (!newVal) {
scope.dateInput = null;
} else {
scope.dateInput = dateFilter(scope.date, 'MM/dd/yyyy');
}
}
});
scope.getDatePattern = function () {
var exp = '/';
// Removed for brevity
exp += '/';
return exp;
};
scope.$watch('dateInput', function (newVal) {
if (newVal !== null) {
scope.date = new Date(newVal);
scope.tmp = scope.date;
}
});
}
};
JSFiddle here: https://jsfiddle.net/e5qu5rgy/1/
Any help at all is greatly appreciated!
So it looks like the problem can be fixed by changing the
link
function for the directive to be acontroller
function instead, as followsBefore going into production, the
controller
needs to be changed over to use an array for its arguments to protect against minification.