Original address: Http://stackoverflow.com/questions/15417125/submit-form-on-pressing-enter-with-angularjs
Scenario 1:
If you want to call function without form you can use my ngenter directive:
Javascript:
function () { returnfunction(scope, element, attrs) { element.bind (function (event) { if(Event.which = = =) { scope. $apply (function () { scope. $eval (Attrs.ngenter, {' event ': Event}); }); Event.preventdefault (); });
HTML:
<ng-app= "" ng-controller= "Mainctrl"> <type= "text" ng-enter= "dosomething ()"> </div>
Scenario 2:
I wanted something a little more extensible/semantic than the given answers so I wrote a directive that takes a JavaScript Object in a similar the built-in ngClass
:
Html
<key-bind= "{enter: ' Go () ', ESC: ' Clear () '}" type= "text" ></input>
The values of the object is evaluated in the context of the directive ' s scope-ensure they is encased in single quotes Otherwise all of the functions would be executed when the directive is loaded (!)
So for example: esc : ‘clear()‘
instead ofesc : clear()
Javascript
MyModule. Constant (' Keycodes ', {ESC:27, Space:32, enter:13, Tab:9, BACKSPACE:8, Shift:16, Ctrl:17, alt:18, CapsLock:20, NumLock:144}). directive (' Keybind ', [' keycodes ',function(keycodes) {functionMap (obj) {varMapped = {}; for(varKeyinchobj) { varAction =Obj[key]; if(Keycodes.hasownproperty (key)) {Mapped[keycodes[key]]=Action; } } returnmapped; } return function(scope, element, Attrs) {varBindings =map (scope. $eval (Attrs.keybind)); Element.bind ("KeyDown keypress",function(event) {if(Bindings.hasownproperty (Event.which)) {scope. $apply (function() {scope. $eval (Bindings[event.which]); }); } }); }; }]);
Submit form on pressing Enter with AngularJS