2

假设我有一个由 ngPattern 验证的当前有效的文本框。我现在将正则表达式更改为与文本框值不匹配的正则表达式。Angular 不会立即发现文本框现在无效 - 用户必须进行更改(例如,键入另一个字母)才能对新的正则表达式进行验证。

一种解决方法是在正则表达式更改时通过将 $viewValue 设置为自身来强制解析管道运行,例如:

看法

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

控制器

// 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 

但是,这似乎是一个大技巧,我希望有一种更好的方法可以做到这一点,而无需求助于自定义指令。

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

4

1 回答 1

4

到目前为止,我已经通过将 $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 />

如果有更好的方法可以做到这一点,我仍然很感兴趣。

于 2014-06-04T04:38:11.393 回答