Angular submit action on enter key press

I’ve faced an issue previously whilst attempting to call an action from pressing enter inside an input box.

This can be done if the input is inside a form using ngSubmit

1
2
3
4

<form ng-submit="Controller.action()">
<input type="text" data-ng-model="Controller.data.field" />
</form>

but outside of a form, this has no use.

so enter the enter directive…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* angular press enter call a function
*
* Logic exported from ng-click function as largely foes the same thing
*/
(function() {
angular.module('MyApp')
.directive("pressEnter", pressEnter);

pressEnter.$inject = ['$parse'];

function pressEnter($parse) {

return {
restrict: 'A',
compile: function ($element, attr) {

var fn = $parse(attr['pressEnter'], /* interceptorFn */ null, /* expensiveChecks */ true);
return function ngEventHandler(scope, element) {
element.on('keydown', function(event) {

if(event.which == 13 && event.shiftKey == false) {
var callback = function () {
fn(scope, {$event: event});
};

scope.$apply(callback);
}
});
};
}
};
}
})();

Gist on github

The logic is the same as the ngClick directive, taken from core, then repurposed for this.

You can now use this in your html as you would ngClick

1
<input type="text" data-press-enter="Controller.action()" data-ng-model="Controller.data.field" />