我将以下指令放在使用 angular-ui-bootstrap 日期选择器的输入字段上:
angular.module('directives.validators.date', [])
.directive('validDate',[ '$filter', function ($filter) {
return {
restrict:'A',
require:'ngModel',
link: function (scope, el, attrs, ngModel) {
var pattern = /^(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19|20)\d\d$/;
ngModel.scope = scope;
ngModel.attrs = attrs;
el.on('blur',function() {
if(typeof ngModel.$viewValue === "object"){
var str = $filter('date')(ngModel.$viewValue, "dd.MM.yyyy");
ngModel.$setViewValue(str);
}
if(ngModel.$viewValue){
if(ngModel.$viewValue!=="" && !pattern.test(ngModel.$viewValue)){
ngModel.$setValidity("date",false);
}
}
});
scope.$watch(function () {
return ngModel.$modelValue;
},
function() {
if(ngModel.$pristine){ //if the data has just been fetched, convert it to date format.
if (typeof ngModel.$viewValue === "number"){
var date = new Date(ngModel.$viewValue);
//var str = $filter('date')(date, "dd.MM.yyyy");
ngModel.$setViewValue(date);
ngModel.$setPristine(true);
var formName = $("form")[0].name;
ngModel.scope[formName].$setPristine(true);
ngModel.$setValidity("date",true);
}
}
if(ngModel.$viewValue){ //when the filed is changed, if it is corrected set that the date is valid
if(ngModel.$viewValue==="" || pattern.test(ngModel.$viewValue)){
ngModel.$setValidity("date",true);
}
}
});
}
};
}]);
我的日期选择器组件有问题,如果没有触及日期选择器字段(即使其中有数据,例如当我编辑资源时),我的表单将不会提交。即使提交了一个好的日期,它基本上也将表单视为无效。该指令修复了该问题,但是当我将 angular 升级到 1.3 时,该指令不再有效。
我需要更改什么才能使该指令再次生效?
最佳答案
Here您可以找到有关影响 1.3 中 ngModel 的重大更改的信息:
Since the HTML5 pattern validation constraint validates the input value, we should also validate against the viewValue. While this worked in core up to Angular 1.2, in 1.3, we changed not only validation, but the way
input[date]
andinput[number]
are handled - they parse their input values intoDate
andNumber
respectively, which cannot be validated by a regex ...
关于javascript - 将 Angular 从 1.2 更新到 1.3 破坏了我的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29894672/