Javascript 如何在更改ngPattern使用的正则表达式时立即重新验证
假设我有一个由当前有效的ngPattern验证的文本框。我现在将正则表达式更改为与文本框的值不匹配的正则表达式。Angular不会立即发现文本框现在无效-用户必须进行更改(例如,键入另一个字母)以根据新的正则表达式进行验证 一种解决方法是,每当正则表达式发生更改时,通过将$viewValue设置为自身,强制解析管道运行,例如: 查看Javascript 如何在更改ngPattern使用的正则表达式时立即重新验证,javascript,angularjs,validation,ng-pattern,Javascript,Angularjs,Validation,Ng Pattern,假设我有一个由当前有效的ngPattern验证的文本框。我现在将正则表达式更改为与文本框的值不匹配的正则表达式。Angular不会立即发现文本框现在无效-用户必须进行更改(例如,键入另一个字母)以根据新的正则表达式进行验证 一种解决方法是,每当正则表达式发生更改时,通过将$viewValue设置为自身,强制解析管道运行,例如: 查看 <div ng-form="form"> <input type="text" name="val" ng-model="myValue"
<div ng-form="form">
<input type="text" name="val" ng-model="myValue" ng-pattern="myRegex" />
</div>
然而,这似乎是一个大难题,我希望有一个更好的方法来做到这一点,而不诉诸于自定义指令
Fiddle:到目前为止,我已经通过将$setViewValue调用移动到指令中来解决了这个明显的限制,该指令至少遵循了控制器不应该关心视图的原则:
// Causes immediate re-validation of the model when ngPattern's regex is changed,
// rather than waiting for the user to manually change the value.
myModule.directive('ngPatternImmediate', [
function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ngModelCtrl) {
scope.$watch(function() {
// watch for change of regex
return scope.$eval(attrs.ngPattern);
}, function() {
// force parsing pipeline to run
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
});
}
};
}
]);
然后可以这样使用它:
<input type="text" ng-model="myValue" ng-pattern="myRegex" ng-pattern-immediate />
不过,我仍然对是否有更好的方法感兴趣。到目前为止,我已经通过将$setViewValue调用移动到指令中来解决了这个明显的限制,该指令至少遵循了控制器不应关心视图的原则:
// Causes immediate re-validation of the model when ngPattern's regex is changed,
// rather than waiting for the user to manually change the value.
myModule.directive('ngPatternImmediate', [
function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ngModelCtrl) {
scope.$watch(function() {
// watch for change of regex
return scope.$eval(attrs.ngPattern);
}, function() {
// force parsing pipeline to run
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
});
}
};
}
]);
然后可以这样使用它:
<input type="text" ng-model="myValue" ng-pattern="myRegex" ng-pattern-immediate />
我仍然有兴趣,如果有一个更好的方法来做到这一点,虽然