Submit form on pressing Enter with AngularJS
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Submit form on pressing Enter with AngularJS相关的知识,希望对你有一定的参考价值。
原文地址:http://stackoverflow.com/questions/15417125/submit-form-on-pressing-enter-with-angularjs
方案1:
If you want to call function without form you can use my ngEnter directive:
Javascript:
angular.module(‘yourModuleName‘).directive(‘ngEnter‘, function() { return function(scope, element, attrs) { element.bind("keydown keypress", function(event) { if(event.which === 13) { scope.$apply(function(){ scope.$eval(attrs.ngEnter, {‘event‘: event}); }); event.preventDefault(); } }); }; });
HTML:
<div ng-app="" ng-controller="MainCtrl"> <input type="text" ng-enter="doSomething()"> </div>
方案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 way to the built-in ngClass
:
html
<input key-bind="{ enter: ‘go()‘, esc: ‘clear()‘ }" type="text"></input>
The values of the object are evaluated in the context of the directive‘s scope - ensure they are encased in single quotes otherwise all of the functions will be executed when the directive is loaded(!)
So for example: esc : ‘clear()‘
instead of esc : 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) { function map(obj) { var mapped = {}; for (var key in obj) { var action = obj[key]; if (keyCodes.hasOwnProperty(key)) { mapped[keyCodes[key]] = action; } } return mapped; } return function (scope, element, attrs) { var bindings = 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的主要内容,如果未能解决你的问题,请参考以下文章
select2 在 form.submit 上清除了多项选择(ruby on rails)