Home > Back-end >  Angular js Directive to Fire "click" event on pressing enter key on ANY element
Angular js Directive to Fire "click" event on pressing enter key on ANY element

Time:01-04

I need to fire the click event using the enter key using a directive. I need it to be a directive because I would like to reuse it.

Ex: A div which has some onclick events bound to it, I will set focus on the div using the tabindex="0" and keyboard enter keydown to fire the click event.

Is this possible? I have tried below code for a directive but it doesnt work.

(function () {
'use strict';

angular
    .module('app.directives')
    .directive('enterKeyInput', enterKeyInput);

enterKeyInput.$inject = [];

/* @ngInject */
function enterKeyInput() {

    var directive = {
        restrict: 'AC',
        link: function (scope, element, attrs) {
            element.bind("keydown keypress", function (event) {
                if (event.keyCode === 13) {
                    element.click();
                }
            });
        }
    };

    return directive;
}

})();

CodePudding user response:

(function () {
'use strict';

angular
    .module('app.directives')
    .directive('enterKeyInput', enterKeyInput);

enterKeyInput.$inject = [];

/* @ngInject */
function enterKeyInput() {

    return {
        restrict: 'AC',
        link: function (scope, element, attrs) {
            element.bind('keyup', function (e)  {
                if ([13].indexOf(e.which) !== -1)  {
                    e.preventDefault();
                    e.stopPropagation();
                    element.click();
                }
            });
        }
    };
}

})();

  •  Tags:  
  • Related