Skip to content

Instantly share code, notes, and snippets.

@samuelsmal
Created January 14, 2016 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuelsmal/6951c31cfff2b217a6cf to your computer and use it in GitHub Desktop.
Save samuelsmal/6951c31cfff2b217a6cf to your computer and use it in GitHub Desktop.
onEnter angular directive
/* global angular: false */
(function () {
'use strict'
angular
.module('sam.utils')
.directive('onEnter', onEnter)
function onEnter () {
return function (scope, element, attrs) {
element.bind('keydown keypress', function (event) {
if (event.keyCode === 13) {
scope.$apply(function () {
scope.$eval(attrs.onEnter)
})
event.preventDefault()
}
})
}
}
})()
@adamreisnz
Copy link

adamreisnz commented Apr 19, 2017

Slightly revised and cleaned up directive, useful for applying on a whole form (while ignoring textareas).

/**
 * Module definition and dependencies
 */
angular.module('Shared.OnEnter.Directive', [])

/**
 * Directive
 */
.directive('onEnter', function($timeout) {
  return {
    restrict: 'A',
    link(scope, element, attrs) {
      element.on('keydown keypress', event => {

        //Check event
        const key = event.keyCode || event.which;
        const isEnter = (key === 13);
        const isTextarea = (event.target.tagName === 'TEXTAREA');

        //Handle event
        if (isEnter && !isTextarea && !event.defaultPrevented) {
          event.preventDefault();
          $timeout(() => {
            scope.$eval(attrs.onEnter);
          });
        }
      });
    },
  };
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment