2

I wrote custom AngularJS directive that dynamically adds ng-pattern and do some other stuff.

It works, but in Chrome and Internet Explorer, if the user tries to enter chars in the middle of existing string, the cursor jumps to the end of the string. In Firefox it works fine.

(Tested with 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/

Why does it happened? And who can I fix that?

Thanks!

3
  • so you mean if you dont have validation-directive it works fine? Commented Aug 16, 2015 at 14:12
  • 1
    if you really want to write a custom validation, you should require ngModel in your directive and add it to $validators object, but if this is good enough for you maybe you can provide a fiddle? Commented Aug 16, 2015 at 14:38
  • @Mikey we could make this directive working..just need to follow what I did in my answer Commented Aug 16, 2015 at 15:00

1 Answer 1

1

Basically you need to remove the directive attribute and add ng-pattern attribute from its compile function itself. Because inside compile function you have raw DOM which doesn't have scope populated with.

To make our directive to get execute first we need to add highest priority to it, so that this directive gets compile first then by terminal: true will disallow to execute other directive on the element like ng-model.

In the Link function produced by the compile function will compile the element that will have our actual manipulated DOM which has ng-pattern working.

Directivee

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.