我有 2 个输入字段需要在输入两个字段后进行验证。这是信用卡到期日,所以有一个month
和year
。我正在使用第三方服务来实际进行验证。
因此,我设置了 3 个指令:exp
、expMonth
和expYear
.
我使用 a$watch
来验证用户输入 - 但是如果验证为假,我想显示一个错误。当我尝试处理时ng-class
,exampleForm.$error.expiry
我得到Error: [$rootScope:infdig] 10 $digest() iterations reached.
这是一个演示 http://plnkr.co/edit/SSiSfLB8hEEb4mrdgaoO?p=preview
视图.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);
};
};
};
}]);