加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 09:36:54 所属栏目:安全 来源:网络整理
导读:在这种特殊情况下,我必须使这些输入调用一个函数,当我按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 -- /
在这种特殊情况下,我必须使这些输入调用一个函数,当我按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');
    };
}])
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有一个很好的解决方案:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读