我有一个包含几个字段的表单,但是选择和输入字段是耦合的:输入的验证取决于用户在选择字段中选择的值。
我将尝试用一个例子来澄清。假设选择包含行星的名称:
<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 http://plnkr.co/edit/t2xMPy1ehVFA5KNEDfrf?p=preview
每当修改选择时,我都需要再次验证输入。这在我的代码中没有发生。我究竟做错了什么?