0

I want to normally work my directive When I add this element by click event.

I checked that the originally declared code works as expected.

This html element is added by javascript function when be called some click event

<input type="text" reg="'^[-+]?([0-9]|[0-8][0-9]|9[0])$'" reg-check>

Here is my directive code

TEST.directive('regCheck', function(){
    return {
        restrict : 'A',
        scope: {
            reg : '='
        },
        link : function(scope, element, attrs){
            var regEx = new RegExp(scope.reg);
            var previousValue;
            console.log(regEx);
            $(element).on('keyup' ,function(){
                var dInput = element[0].value
                console.log(dInput);
                if(regEx.test(dInput) || dInput =='' || dInput =='-') previousValue = dInput
                else element[0].value = previousValue
            });
        }
    }
})

I think that this problem works cause by jquery event not rendered to added element. So I try to

$(document).on('keyup', element ,function(){
     var dInput = element[0].value
     console.log(dInput);
     if(regEx.test(dInput) || dInput =='' || dInput =='-') previousValue = dInput
     else element[0].value = previousValue
});

It's not work too. What should I do?

1
  • that element code shown by ng-bind-html Commented Jul 23, 2018 at 6:58

1 Answer 1

1

I think you are unable to have your directive fire on the keyup event?

$ is not defined. Simple mod gets you going:

app.directive('regCheck', function(){
  return {
    restrict : 'A',
    require: 'ngModel',
    scope: {
        reg : '='
    },
    link : function(scope, element, attrs, ngModel){
        var regEx = new RegExp(scope.reg);
        var previousValue;
        console.log(regEx);
        element.on('keyup' ,(ngModel) => {
            console.log('value', ngModel.target.value);
            var dInput = element[0].value
            console.log(dInput);
            if(regEx.test(dInput) || dInput =='' || dInput =='-') previousValue = dInput
            else element[0].value = previousValue
        });
    }
  }
})

And add a ng-model to your input and the value of the input is output to the console on every keyUp event.

<input type="text" ng-model="inputValue" reg-check reg="'^[-+]?([0-9]|[0-8][0-9]|9[0])$'">

Note: I did not check the logic of the directive or regEx as I dont think that was the question.

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

1 Comment

I solved problem. the problem is that after added elements by javascript are not checked by $complie So angular can't check that element. Thank you for your helping. I referenced this

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.