简体   繁体   English

更改ngPattern使用的正则表达式时如何立即重新验证

[英]How to re-validate immediately when changing regex used by ngPattern

Say I have a textbox validated by ngPattern that is currently valid. 假设我有一个由ngPattern验证的文本框,该文本框当前有效。 I now change the regex to one that does not match the textbox's value. 现在,我将正则表达式更改为与文本框值不匹配的正则表达式。 Angular does not immediately pick up that the textbox is now invalid - the user must make a change (eg. type another letter) to cause validation against the new regex to occur. Angular不会立即得知该文本框现在是无效的-用户必须进行更改(例如,键入另一个字母)以引起针对新正则表达式的验证。

A workaround is to force the parsing pipeline to run by setting the $viewValue to itself whenever the regex changes, eg: 一种解决方法是通过在正则表达式发生更改时将$ viewValue设置为其自身来强制运行解析管道,例如:

View 视图

<div ng-form="form">
    <input type="text" name="val" ng-model="myValue" ng-pattern="myRegex" />
</div>

Controller 调节器

// set a new regex for the ng-pattern directive and force re-validation
$scope.myRegex = new RegExp('^[a-z]$');
$scope.form.val.$setViewValue($scope.form.val.$viewValue); // yuck 

However, this seems like a big hack and I'm hoping there is a nicer way to do this without resorting to a custom directive. 但是,这似乎是一个很大的漏洞,并且我希望有一种更好的方法来执行此操作,而无需诉诸自定义指令。

Fiddle: http://jsfiddle.net/5jm2V/2/ 小提琴: http : //jsfiddle.net/5jm2V/2/

So far I have worked around this apparent limitation by moving the $setViewValue call into a directive, which at least adheres to the principle that controllers should not concern themselves with views: 到目前为止,我已经通过将$ 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);
                });
            }
        };
    }
]);

It can then be used like this: 然后可以这样使用:

<input type="text" ng-model="myValue" ng-pattern="myRegex" ng-pattern-immediate />

I am still interested if there is a better way to do this though. 不过,我仍然对是否有更好的方法感兴趣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM