小编典典

使用AngularJS按Enter提交表单

angularjs

在这种特殊情况下,按Enter键时必须使这些输入调用函数的选项是什么?

// HTML view //
<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');
    };
}])

阅读 211

收藏
2020-07-04

共1个答案

小编典典

Angular开箱即用。您是否在表单元素上尝试了ngSubmit

<form ng-submit="myFunc()" ng-controller="mycontroller">
   <input type="text" ng-model="name" />
    <br />
    <input type="text" ng-model="email" />
</form>

编辑:根据有关提交按钮的注释,该解决方案包括:

<input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;"/>

如果您不喜欢隐藏的提交按钮解决方案,则需要将控制器功能绑定到Enter
keypress或keyup事件。这通常需要一个自定义指令,但是AngularUI库已经设置了一个不错的按键解决方案。见http://angular-
ui.github.com/

添加angularUI库之后,您的代码将类似于:

<form ui-keypress="{13:'myFunc($event)'}">
  ... input fields ...
</form>

或者您可以将Enter键绑定到每个单独的字段。

编辑(2014-08-28):在编写此答案时,ng-keypress / ng-keyup/ng-keydown在AngularJS中不作为本机指令存在。在下面的评论中,@darlan-alves提供了一个很好的解决方案:

<input ng-keyup="$event.keyCode == 13 && myFunc()"... />

2020-07-04