我知道这在不久前就得到了回答,但我遇到了类似的问题,我设法从一堆其他答案和一些试验和错误中拼凑出一个合适的解决方案。我想有一天其他人可能会寻找类似的东西......
这是一种(据我所知)直接与验证系统相关的方法。这个特定示例创建了一个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对象上的$validators,这是其他验证器(必填字段,最小长度,. ..) 似乎还活着。这会在字段上设置验证,但该规则仅在具有匹配指令的字段更新时才会处理。
为了解决这个问题,然后在目标模型上设置了一个手表。当目标模型的值更新时,它将在原始控件上运行$validate() 方法,允许在两个字段中的任何一个字段中进行验证。