我有一个包含很少字段的表单,但是select和input字段是耦合的:输入的验证取决于用户在select字段中选择的值.
我将尝试用一个例子来澄清.假设选择包含行星的名称:
<select id="planet" class="form-control" name="planet" ng-model="planet" ng-options="c.val as c.label for c in planets"></select>
在输入中,我通过名为“input-validation”的自定义指令应用自定义验证:
<input id="city" input-validation iv-allow-if="planet==='earth'" class="form-control" name="city" ng-model="city" required>
这是指令:
.directive('inputValidation',[function() { return { require: 'ngModel',restrict: 'A',scope: { ivAllowIf: '=' },link: function(scope,elm,attrs,ctrl) { ctrl.$parsers.unshift(function(viewValue) { //input is allowed if the attribute is not present or the expression evaluates to true var inputAllowed = attrs.ivAllowIf === undefined || scope.$parent.$eval(attrs.ivAllowIf); if (inputAllowed) { ctrl.$setValidity('iv',true); return viewValue; } else { ctrl.$setValidity('iv',false); return undefined; } }); } }; }])
可以在Plnkr:http://plnkr.co/edit/t2xMPy1ehVFA5KNEDfrf?p=preview中检查完整的示例
解决方法
我已经做了同样的事情来验证结束日期更改的开始日期.在开始日期的指令中添加watch来更改结束日期,然后调用ngModel.$validate()以防定义结束日期新值.
scope.$watch(function () { return $parse(attrs.endDate)(scope); },function () { ngModel.$validate(); });
要采取的重要部分是在指令中调用ngModel.$validate().
注意
您应该使用$validators进行上述自定义验证. read here,$parsers是旧方法 – 来自angularjs 1.3使用$validators