AngularJS自定义验证指令:光标跳到字符串的末尾

AngularJS自定义验证指令:光标跳到字符串的末尾,angularjs,google-chrome,internet-explorer,angularjs-directive,Angularjs,Google Chrome,Internet Explorer,Angularjs Directive,我编写了自定义AngularJS指令,动态添加ng模式并执行其他一些操作 它是有效的,但是在Chrome和Internet Explorer中,如果用户试图在现有字符串的中间输入字符,则游标跳转到字符串的结尾。在Firefox中,它运行良好 (使用Chrome 44、Firefox 40、IE 11进行测试) HTML: 为什么会这样?我能帮谁解决这个问题 谢谢 基本上,您需要删除directive属性,并从编译函数本身添加ng pattern属性。因为在编译函数中,您有原始DOM,它没有填充

我编写了自定义AngularJS指令,动态添加ng模式并执行其他一些操作

它是有效的,但是在Chrome和Internet Explorer中,如果用户试图在现有字符串的中间输入字符,则游标跳转到字符串的结尾。在Firefox中,它运行良好

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

HTML:

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


谢谢

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

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

在由compile函数生成的Link函数中,compile函数将编译具有实际操作的DOM的元素,该DOM具有
ng模式
工作

指导

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);
            }
        }
    };
});

那么您的意思是,如果您没有验证指令,它可以正常工作?如果您真的想编写自定义验证,您应该在指令中要求ngModel,并将其添加到
$validators
对象,但是如果这对你来说足够好的话,也许你可以提供一把小提琴?@Mikey我们可以让这个指令生效……只需要按照我在回答中所做的去做
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);
        }
    };
});
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);
            }
        }
    };
});