因此,当前代码如下所示:
<input ng-pattern="validRegEx()" required>
$scope.validRegEx = function() {
// blah blah return regex
};
当我更改表单上的输入时,我更改了正则表达式。问题是之前有效的数据(对于新的 RegEx 不应该有效)仍然有效。如何强制表单再次将正则表达式应用于该字段,而不是等待用户再次模糊该字段?
因此,当前代码如下所示:
<input ng-pattern="validRegEx()" required>
$scope.validRegEx = function() {
// blah blah return regex
};
当我更改表单上的输入时,我更改了正则表达式。问题是之前有效的数据(对于新的 RegEx 不应该有效)仍然有效。如何强制表单再次将正则表达式应用于该字段,而不是等待用户再次模糊该字段?
您可以通过观察正则表达式何时更改(或其条件)以及何时更改来通过重新设置元素的值来重新运行验证来执行此操作。
像这样的东西
angular.module('youappname', [])
.directive('reApply', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, elm, attrs, ctrl) {
// you should change 'regex' in the following line to match the variable that when altered causes the regex to change..
scope.$watch('regex', function (value) {
if (ctrl.$viewValue !== ''){
ctrl.$setViewValue( ctrl.$viewValue );
}
});
}
};
});
并添加re-apply
到您的元素
<input type="text" ng-pattern="validate()" re-apply="" name="userName" ng-model="user.name" required> <span class="error" ng-show="myForm.userName.$error.required">
这也可以直接在控制器中完成。这将监视输入的 stuff.name,如果它发生变化,它将清除 scope.stuff.results 字段。
$scope.$watch("stuff.name", function(newValue, oldValue){
if(newValue != oldValue)
$scope.stuff.results = "";
});