Search code examples
javascriptangularjsangularjs-directiveclickenter

Angular js Directive to Fire "click" event on pressing enter key on ANY element


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

})();


Solution

  • Found the answer myself :D

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

    })();