动态更新';最大值';AngularJS中的验证
编辑:大量简化以触及问题的核心 在角度(v1.2.22)验证中,如果动态更新';最大值';AngularJS中的验证,angularjs,validation,min,Angularjs,Validation,Min,编辑:大量简化以触及问题的核心 在角度(v1.2.22)验证中,如果max的值取决于另一个值,并且该值更新,则验证状态不会自动更新 var app = angular.module('app',[]). controller('TestCtrl', function($scope){ $scope.partWidth = 10; }); HTML: 零件宽度 刀具宽度 更新的Plunker 除非编辑了cutterwidth本身,否则不会删除ng invalid类 a) 这是虫子吗 b
max
的值取决于另一个值,并且该值更新,则验证状态不会自动更新
var app = angular.module('app',[]).
controller('TestCtrl', function($scope){
$scope.partWidth = 10;
});
HTML:
零件宽度
刀具宽度
更新的Plunker
除非编辑了cutterwidth
本身,否则不会删除ng invalid
类
a) 这是虫子吗
b) 有解决办法吗?(例如,强制运行验证,以某种方式触发输入事件等)实际上,您遗漏了逻辑中的一些细节 对于PartWidth,您需要做的是检查用户是否输入了低于10或低于
切割器宽度的内容。因此,一个getMax
函数应该可以做到这一点
<input id="width" name="width" min="{{ getMax(10, cutterwidth) }}" max="180" ng-model="width" placeholder="mm" required type="number">
getMax
函数非常简单。只需反转getMin
函数即可
这是我想是的
b) 我的解决办法是,在经历了大量史诗般的斗争之后,避免完全使用本机的max
属性,而是构建一个自定义指令
我将ngAppMax
属性公开给scope,并使用=
传递ngModel
。我不完全理解这一点,但它是有效的
然后比较这两个值,并在模型上使用$setValidity
(名为“ctrl”)
,或参阅下文:
HTML
<form name="itemForm">
<input name="partWidth" min="10" max="300" ng-model="partWidth" placeholder="mm" required type="number">
<input name="cutterwidth" min="10" ng-app-max="{{ partWidth }}" ng-model="cutterWidth" placeholder="mm" required type="number">
</form>
有趣的是,如果您查看呈现页面中cutterwidth
的max=“
属性,它会随着partwidth值的更改而实时更新。但是,Angular仅在编辑刀具宽度本身时删除ng invalid
类,当max
的值更改时不会触发该类。这是一个bug吗?我可以补充一下,但是partWidth不需要依赖于切割器的宽度,这实际上并不能解决问题。也许我解释得不够好。好吧,我重读了你的问题。对不起,回答错了。如果我能解决这个问题,我会更新答案。我已经把它完全改写为一个简化的场景。希望现在更清楚。
<form name="itemForm">
<input name="partWidth" min="10" max="300" ng-model="partWidth" placeholder="mm" required type="number">
<input name="cutterwidth" min="10" ng-app-max="{{ partWidth }}" ng-model="cutterWidth" placeholder="mm" required type="number">
</form>
angular.module('app',[]).
controller('TestCtrl', function($scope){}).
directive('ngAppMax', function(){
return {
require: 'ngModel',
scope: {
ngAppMax: '@',
ngModel: '='
},
link: function(scope, element, attrs, ctrl){
scope.$watch('ngAppMax', function(newVal){
validate(scope.ngModel, newVal, ctrl);
});
scope.$watch('ngModel', function(val){
validate(val, scope.ngAppMax);
});
function validate(thisVal, maxVal){
if(thisVal > maxVal){
ctrl.$setValidity('range', false);
} else {
ctrl.$setValidity('range', true);
}
}
}
}
});