[英]Custom expiration date directive throwing rootScope digest error
輸入兩個字段后,我需要2個輸入字段進行驗證。 這是信用卡的到期日,所以有month
和year
。 我正在使用第三方服務來實際進行驗證。
因此,我設置了3個指令: exp
, expMonth
和expYear
。
我使用$watch
驗證用戶輸入-但是,如果驗證為假,我想顯示一個錯誤。 當我嘗試使用exampleForm.$error.expiry
進行ng-class
,出現Error: [$rootScope:infdig] 10 $digest() iterations reached.
這是一個演示 http://plnkr.co/edit/SSiSfLB8hEEb4mrdgaoO?p=preview
view.html
<form name='exampleForm' novalidate>
<div class="form-group" ng-class="{ 'is-invalid': exampleForm.$error.expiry }">
<div class="expiration-wrapper" exp>
<input type='text' ng-model='data.year' name='year' exp-month />
<input type='text' ng-model='data.month' name='month' exp-year />
</div>
</div>
exp.directive.js
angular.module('example')
.directive('exp', ['ThirdPartyValidationService',
function(ThirdPartyValidationService) {
return {
restrict: 'A',
require: 'exp',
link: function(scope, element, attrs, ctrl) {
ctrl.watch();
},
controller: function($scope, $element, ThirdPartyValidationService) {
var self = this;
var parentForm = $element.inheritedData('$formController');
var ngModel = {
year: {},
month: {}
};
var setValidity = function(exp) {
var expMonth = exp.month;
var expYear = exp.year;
var valid = ThirdPartyValidationService.validateExpiry(expMonth, expYear);
parentForm.$setValidity('expiry', valid, $element);
};
self.setMonth(monthCtrl) {
ngModel.month = monthCtrl;
};
self.setYear(yearCtrl) {
ngModel.year = yearCtrl;
};
self.watch = function() {
$scope.$watch(function() {
return {
month: ngModel.month.$modelValue,
year: ngModel.year.$modelValue
};
}, setValidity, true);
};
}
};
}]);
expMonth.directive.js
angular.module('example')
.directive('expMonth', [
function() {
return {
restrict: 'A',
require: ['ngModel', '^?exp'],
compile: function(element, attributes) {
return function(scope, element, attributes, controllers) {
var formCtrl = controllers[0];
var expMonthCtrl = controllers[1];
expMonthCtrl.setMonth(formCtrl);
};
};
};
}]);
expYear.directive.js
angular.module('example')
.directive('expYear', [
function() {
return {
restrict: 'A',
require: ['ngModel', '^?exp'],
compile: function(element, attributes) {
return function(scope, element, attributes, controllers) {
var formCtrl = controllers[0];
var expYearCtrl = controllers[1];
expYearCtrl.setYear(formCtrl);
};
};
};
}]);
問題是您正在使用以下行將有效性錯誤設置為jquery選擇:
parentForm.$setValidity('expiry', valid, $element);
然后,當您擁有以下內容時,您將通過ng-class
觀看該jQuery元素:
ng-class="{ 'is-invalid' : exampleForm.$error.expiry }"
在您的標記中。 當angular嘗試深復制該值時,這將引發奇怪的異常。
而是將其更改為使用jQuery對象的.length
屬性。 如果非零(真實),則將正確設置is-invalid
類,否則將不會設置。
ng-class="{ 'is-invalid' : exampleForm.$error.expiry.length }"
如果這對您和將來必須查看您的代碼的開發人員更有意義,您也可以...expiry.length > 0
。
我分叉了您的Plunkr,因此可以進行此更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.