我已经为我的表单创建了一个验证指令.
它基本上根据来自另一个字段的数据验证字段值.
它基本上根据来自另一个字段的数据验证字段值.
它完美无缺:-)
我的问题是,如果在执行验证后其他字段发生更改,则验证将不再运行.
var myApp = angular.module('myApp',[]) .directive('validateInteger',function() { return { require: 'ngModel',link: function(scope,elm,attrs,ctrl) { ctrl.$parsers.unshift(function(viewValue) { var int1val = scope.int1; scope.int2valid = (viewValue > int1val) ? "valid" : undefined; if (scope.int2valid == "valid") { ctrl.$setValidity('higher',true); return viewValue; } else { ctrl.$setValidity('higher',false); return undefined; } }); } }; });
jsfiddle:http://jsfiddle.net/hanspc/vCFFQ/
解决方法
明确引用指令中的某些字段是一个非常糟糕的主意.正如您所看到的,这有许多缺点:不可移植性,代码重复,脆弱性,……
做这样的事情:
<input type="text" ng-model="int2" validate-greater-integer="int1" />
而且:
myApp.directive('validateGreaterInteger',function() { return { require: 'ngModel',scope: { otherInteger : '=validateGreaterInteger',} link: function(scope,ctrl) { ctrl.$parsers.unshift(function(viewValue) { if (viewValue > scope.otherInteger) { ctrl.$setValidity('higher',true); return viewValue; } else { ctrl.$setValidity('higher',false); return undefined; } } });
然后,您可以简单地执行the typical state control(有关示例,请参阅“绑定到窗体和控件状态”部分).
请注意,在这种情况下,您还可以更简单地使用input[number]及其min参数.
在评论讨论后编辑:
好吧,NgModelController.$解析器中的函数显然只在模型内容发生变化时才被调用.你想要做的是在int1或int2改变时进行验证.所以就这样做:-):
link: function(scope,ctrl) { scope.$watch('data',function (data) { if (data.int2 > data.int1) { ctrl.$setValidity('higher',true); return data.int2; } else { ctrl.$setValidity('higher',false); return undefined; } },true);
使用你自己的验证变量(你的小提琴中的int2valid)也很奇怪.请使用the typical state control,类似于form.int2.$error.higher.