0

In my angular view, I am using directive to render an input field and it works fine. But now I required to perform some action on keydown.

ng-keydown works fine with the input field I have in my view:

<input ng-keydown="tabed($event)" ng-model="myData2"/>

but it is not working with the input field which is rendered via directive

<my_input input-value="mydata"></my_input>

Directive:

app.directive('myInput', function () {
  return {
    restrict: 'EA',
    template: '<input ng-keydown="tabed($event)" ng-model="inputValue"/>',
    scope: {
        inputValue: '=',
        inputName: '='
    },
    link: function (scope) {

    }
  };
});

I have tried a lot but did not found any way to trigger keydown event on input field rendered via directive.

Here is the Fiddle

2 Answers 2

2

That's because your directive created a new child scope, and in it's link function there is no tabed function. You can reference the parents scope via $parent. I highly recommend moving the tabed function to within the directive, but if you just need it this is the change you would need to make:

template: '<input ng-keydown="$parent.tabed($event)" ng-model="inputValue"/>',

jsfiddle: http://jsfiddle.net/JJ5UM/1/

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

1 Comment

Thanks a lot for the quick answer with explanation.
0

I think you can achieve the same effects using $watch instead of ng-keydown

Fiddle

And here's how the directive should look;

app.directive('myInput', function () {
    return {
        restrict: 'EA',
        template: '<input ng-keydown="tabed($event)" ng-model="inputValue"/>',
        scope: {
            inputValue: '=',
            inputName: '='
        },
        link: function (scope) {
            scope.$watch('inputValue', function (now, then) {
                console.debug('yeah, I see the change', now, then);
            });
        }
    };
});

2 Comments

Thanks for the response. I required to perform some action on tab key down so I need to know the key code. It is possible via your approach?
@user1690588 I think not, $watch only checks for value changes. I think in your case ngKeydown is the best way to go forward.

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.