函数 – 使用AngularJS按Enter键提交表单

前端之家收集整理的这篇文章主要介绍了函数 – 使用AngularJS按Enter键提交表单前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在这种特殊情况下,我必须使这些输入调用一个函数,当我按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');
    };
}])
@H_502_4@
Angular支持这种开箱即用。你试过 ngSubmit你的表单元素?
<form ng-submit="myFunc()" ng-controller="mycontroller">
   <input type="text" ng-model="name" />
    <br />
    <input type="text" ng-model="email" />
</form>

编辑:根据关于提交按钮的评论,请参见Submitting a form by pressing enter without a submit button解决方案:

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

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

添加angularUI lib后,你的代码将是:

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

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

另外,看到这个问题,创建一个简单的keypres指令:
How can I detect onKeyUp in AngularJS?

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

原文链接:https://www.f2er.com/angularjs/148065.html

猜你在找的Angularjs相关文章