[英]Updating angular from 1.2 to 1.3 broke my directive
我將以下指令放到使用angular-ui-bootstrap datepicker的輸入字段中:
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);
}
}
});
}
};
}]);
我對datepicker組件有一個問題,即如果未觸摸datepicker字段(即使其中包含數據,例如當我編輯資源時),表單也不會提交。 即使提交的日期正確,它也基本上將表單視為無效。 該指令解決了該問題,但是當我將angular升級到1.3時,該指令不再起作用。
我需要更改什么才能使該指令再次起作用?
在這里,您可以找到有關影響1.3中ngModel的重大更改的信息:
由於HTML5模式驗證約束會驗證輸入值,因此我們還應該針對viewValue進行驗證。 盡管此功能在Angular 1.2之前的Core中一直有效,但在1.3中,我們不僅更改了驗證,還更改了
input[date]
和input[number]
的處理方式-它們分別將輸入值解析為Date
和Number
,無法通過以下方式驗證正則表達式...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.