我目前正在处理一个似乎很常见的问题,但我找不到一个优雅的方法来处理它。问题归结为两个数字输入字段,其中一个字段必须小于另一个字段。为了执行此操作,我使用以下指令来验证较低输入字段的输入,其中scope.maxThreshold是较高输入字段的输入:
testDirectives.directive('maxThreshold', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
if (viewValue > scope.maxThreshold) {
ctrl.$setValidity('thresholdTooHigh', false);
return undefined;
} else {
ctrl.$setValidity('thresholdTooHigh', true);
return viewValue;
}
});
}
};
});
较高输入字段的指令与比较切换非常相似。这一切都很有效,直到用户在收到验证错误后切换他们输入的字段。例如,如果较低字段为5且较高字段为10,则用户将较低字段切换为15.此字段现在标记为具有验证错误。现在,如果用户转到更高的输入字段并输入20,则该字段的指令将触发并验证通过。问题是较低输入字段的有效性仍被标记为无效。处理此问题的最佳方法是什么,并将较低输入字段标记为从较高输入字段使用的指令有效?感谢。
答案 0 :(得分:1)
似乎问题是检查输入的有效性,而不是模型更改。也就是说,如果条件发生变化,您还需要检查有效性。请参阅指令:
这更接近你要找的东西。如果正在编辑最小字段,您似乎无法使最大字段无效。手表功能的另一项检查可以实现这一点。
.directive('highThreshold', function() {
return {
require: 'ngModel',
scope: {
'highThreshold': '='
},
link: function($scope, element, ctrl, ngModel) {
$scope.$watch('highThreshold', function(){
var isValid = ngModel.$modelValue < $scope.highThreshold;
ngModel.$setValidity("highThreshold", isValid);
});
ngModel.$validators.highThreshold = function(value) {
return value < $scope.highThreshold;
};
}
};
})
.directive('lowThreshold', function() {
return {
require: 'ngModel',
scope: {
'lowThreshold': '='
},
link: function($scope, element, attrs, ngModel) {
$scope.$watch('lowThreshold', function(){
var isValid = ngModel.$modelValue > $scope.lowThreshold;
ngModel.$setValidity("lowThreshold", isValid);
});
ngModel.$validators.lowThreshold = function(value) {
return value > $scope.lowThreshold;
};
}
};
});
很抱歉第一次没有得到这个问题:)希望这会有所帮助!