【发布时间】:2015-12-03 15:28:06
【问题描述】:
我正在尝试将<input> 包装在指令中,以便我可以处理日期验证并将其从字符串转换为实际的Date 对象并在原始范围内维护Date 版本。这种交互按预期工作。但是<input> 元素上的ng-pattern 行为不正确。无论输入什么,它都不会使<input> 无效。
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:https://jsfiddle.net/e5qu5rgy/1/
非常感谢任何帮助!
【问题讨论】:
标签: javascript angularjs angularjs-directive angularjs-ng-pattern