【问题标题】:AngularJS custom validation directive: cursor jumps to end of stringAngularJS 自定义验证指令:光标跳转到字符串末尾
【发布时间】:2015-11-09 05:35:14
【问题描述】:

我编写了自定义 AngularJS 指令,动态添加 ng-pattern 并做一些其他事情。

它可以工作,但在 Chrome 和 Internet Explorer 中,如果用户尝试在现有字符串的中间输入字符,光标会跳转到字符串的末尾。在 Firefox 中它工作正常。

(使用 Chrome 44、Firefox 40、IE 11 测试)

HTML:

<input type="text" name="input1" ng-model="value1" validation-directive>

JS:

myApp.directive("validationDirective", function ($compile) {
    return {
        restrict: 'A',
        link: function (scope, element) {
            element.removeAttr('validation-directive'); // necessary to avoid infinite compile loop
            element.attr("ng-pattern", new RegExp("^[a-z]{0,10}$"));
            //Do more stuff...
            $compile(element)(scope);
        }
    };
});

http://jsfiddle.net/y8416aax/

为什么会这样?谁能解决这个问题?

谢谢!

【问题讨论】:

  • 所以你的意思是如果你没有验证指令它工作正常?
  • 如果您真的想编写自定义验证,您应该在指令中要求 ngModel 并将其添加到 $validators 对象,但如果这对您来说足够好,也许您可​​以提供一个小提琴?
  • @Mikey 我们可以使这个指令起作用..只需按照我在回答中所做的操作

标签: angularjs google-chrome internet-explorer angularjs-directive


【解决方案1】:

基本上,您需要从其编译函数本身中删除指令属性并添加ng-pattern 属性。因为在 compile 函数内部你有原始 DOM,它没有填充范围。

要使我们的指令首先执行,我们需要为其添加最高优先级,以便该指令首先编译,然后 terminal: true 将不允许在元素上执行其他指令,例如 ng-model

在 compile 函数生成的 Link 函数中,将编译将具有我们实际操作的 DOM 的元素,该 DOM 具有 ng-pattern 工作。

指令对象

myApp.directive("validationDirective", function ($compile) {
    return {
        restrict: 'A',
        priority: 1001,
        terminal: true,
        compile: function (ele) {
            // necessary to avoid infinite compile loop
            ele.removeAttr('validation-directive'); 
            ele.attr("ng-pattern", new RegExp("^[a-z]{0,10}$"));
            return function (scope, element) {
                $compile(element)(scope);
            }
        }
    };
});

Working Fiddle

【讨论】:

    猜你喜欢
    • 2017-05-26
    • 2014-03-07
    • 2020-02-21
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    • 2015-08-31
    • 2012-01-03
    • 1970-01-01
    相关资源
    最近更新 更多