[英]How to force validation to run on model when other model changes?
我有一个输入字段,其上注册了许多$validators
,用于更新模型。 其中一些验证器与范围上的其他值进行比较(也使用输入字段更新)。
当其他值更改依赖时,如何强制AngularJS再次运行这些验证?
我已经尝试在文档中找到与此相关的任何内容,并且还在依赖字段上创建了一个$watch
并且只是将模型值设置为自身(希望它会强制重新验证),但两者都没有运气。
如果您使用的是Angularjs 1.3+,则可以使用$ validate方法。 让我们说你的输入“A”是依赖于其他输入的那个,我们称之为“B”。 你可以为每个B的$ viewChangeListeners添加一个函数,它只调用A的$ validate方法。 这将产生以下效果; 每次修改B输入之一时,A输入$ validators都会运行。
我知道这回答了一段时间,但我有一个类似的问题,我设法从一堆其他答案和一些试验和错误拼凑出一个合适的解决方案。 我认为其他人有一天可能会寻找类似的东西......
这是一种方法(据我所知)直接与验证系统联系起来。 此特定示例创建match
验证规则,该规则比较两个模型并验证它们的值是否相同。
<script type="text/javascript">
angular.module( "YourModule", [] )
.directive( "match", function() {
return {
require: 'ngModel',
restrict: 'A',
link: function( $scope, $elem, $attrs, $ctrl ) {
// targetModel is the name of the model you want to
// compare against.
var targetModel = $attrs.match;
// Add the 'match' validation method
$ctrl.$validators.match = function( modelValue, viewValue ) {
valid = $scope.$eval( targetModel ) == viewValue;
$ctrl.$setValidity( 'match', valid );
return valid ? viewValue : undefined;
};
// When the target model's value changes, cause this model
// to revalidate
$scope.$watch( targetModel, function() {
$ctrl.$validate();
} );
}
};
} );
然后像这样使用(显然包括表单, ng-app
和ng-controller
):
<input type="password" ng-model="password" />
<input type="password" ng-model="confirmation" match="password" />
一般的想法是,当处理匹配指令时,额外的函数( match
)被添加到$ctrl
对象上的$ctrl
$validators
,这是其他验证器(必需字段,最小长度......)似乎存在的地方。 这会在字段上设置验证,但只有在更新带有match指令的字段时才会处理该规则。
为了解决这个问题,然后在目标模型上设置手表。 更新目标模型的值后,它将在原始控件上运行$validate()
方法,从而允许在两个字段中的任何一个中进行验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.