在AngularJS中,当同一形式的另一个值发生变化时,如何强制重新验
发布时间:2020-12-17 17:25:20 所属栏目:安全 来源:网络整理
导读:我有一个包含很少字段的表单,但是select和input字段是耦合的:输入的验证取决于用户在select字段中选择的值. 我将尝试用一个例子来澄清.假设选择包含行星的名称: select id="planet" class="form-control" name="planet" ng-model="planet" ng-options="c.v
我有一个包含很少字段的表单,但是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(). 注意 FIXED PLUNKER LINK (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |