问题描述
在这种特殊情况下,当我按下 Enter 键时,我有哪些选项可以让这些输入调用函数?
In this particular case, what options do I have to make these inputs call a function when I press Enter?
HTML:
<form>
<input type="text" ng-model="name" <!-- Press ENTER and call myFunc --> />
<br />
<input type="text" ng-model="email" <!-- Press ENTER and call myFunc --> />
</form>
// Controller //
.controller('mycontroller', ['$scope',function($scope) {
$scope.name = '';
$scope.email = '';
// Function to be called when pressing ENTER
$scope.myFunc = function() {
alert('Submitted');
};
}])
推荐答案
Angular 支持开箱即用.您是否在表单元素上尝试过 ngSubmit?
Angular supports this out of the box. Have you tried ngSubmit on your form element?
<form ng-submit="myFunc()" ng-controller="mycontroller">
<input type="text" ng-model="name" />
<br />
<input type="text" ng-model="email" />
</form>
根据关于提交按钮的评论,请参阅 在没有提交按钮的情况下按 Enter 提交表单 给出了以下解决方案:
Per the comment regarding the submit button, see Submitting a form by pressing enter without a submit button which gives the solution of:
<input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;"/>
如果您不喜欢隐藏的提交按钮解决方案,则需要将控制器功能绑定到 Enter keypress 或 keyup 事件.这通常需要自定义指令,但 AngularUI 库已经设置了一个很好的按键解决方案.请参阅http://angular-ui.github.com/
If you don't like the hidden submit button solution, you'll need to bind a controller function to the Enter keypress or keyup event. This normally requires a custom directive, but the AngularUI library has a nice keypress solution set up already. See http://angular-ui.github.com/
添加 angularUI 库后,您的代码将类似于:
After adding the angularUI lib, your code would be something like:
<form ui-keypress="{13:'myFunc($event)'}">
... input fields ...
</form>
或者您可以将回车键绑定到每个单独的字段.
or you can bind the enter keypress to each individual field.
此外,请参阅此 SO 问题以创建简单的 keypres 指令:如何在 AngularJS 中检测 onKeyUp?
Also, see this SO questions for creating a simple keypres directive:How can I detect onKeyUp in AngularJS?
EDIT (2014-08-28):在撰写此答案时,ng-keypress/ng-keyup/ng-keydown 在 AngularJS 中作为本机指令不存在.在下面的评论中@darlan-alves 有一个很好的解决方案:
EDIT (2014-08-28): At the time this answer was written, ng-keypress/ng-keyup/ng-keydown did not exist as native directives in AngularJS. In the comments below @darlan-alves has a pretty good solution with:
<input ng-keyup="$event.keyCode == 13 && myFunc()".../>
这篇关于使用 AngularJS 按 Enter 提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!