AngularJs ng-click 在按下 Enter 按钮时触发两次

Bil*_*son 2 javascript angularjs

所以我有一个带有以下按钮的表单:

<form name="invoiceLine">
  <div class="rTableRow">
    <div class="rTableCell rTableCellXsm" ng-keyup="keyPress($event)">{{invoice_line.line}}</div>
    <div class="rTableCell rTableCellL" >
      <datecomponent style="display: inline-block" model="invoice_line.date" elementid="il2" tabindex="'1'"></datecomponent>
    </div>
    <div class="rTableCell rTableCellXl" ng-keyup="keyPress($event)">
      <input id="invLineDesc" style="width: 90%;" type="text" ng-model="invoice_line.description" ng-maxlength="30" tabindex="2">
      <span class="redtext">*</span>
    <div>{{invoice_line.description.length <= 30 ? 30 - invoice_line.description.length + ' chars remaining' : 'Description too long!' }}</div>
    </div>
    <div class="rTableCell rTableCellL" ng-keyup="keyPress($event)">
      $<input style="width: 50%; margin-left: 5px;" type="text" ng-model="invoice_line.amount" tabindex="3">
     </div>
     <div class="rTableCell rTableCellL">
       <input type="button" class="button {{buttonPrefColor}}" ng-click="add_new_invoice_line()" ng-show="invoiceLine.$dirty" value="Add New" tabindex="4">
       <input type="button" class="button {{buttonPrefColor}}" ng-click="reset_invoice_line_btn()" ng-show="invoiceLine.$dirty" value="Reset" tabindex="5">
     </div>
   </div>
 </form>
Run Code Online (Sandbox Code Playgroud)

但是,如果我切换到Add New按钮并按“Enter”键,那么它会调用 ng-click 函数两次。如果我点击它,它只会触发一次。有任何想法吗?

Sun*_* D. 5

查看该指令的文档form,它对当您在表单上按 Enter 键时 Angular 执行的操作有一些规则:

要防止处理程序的双重执行,请仅使用 ngSubmit 或 ngClick 指令之一。这是因为 HTML 规范中存在以下表单提交规则:

如果表单只有一个输入字段,则在此字段中按 Enter 键会触发表单提交 (ngSubmit)

如果表单有 2 个以上的输入字段且没有按钮或 input[type=submit],则按 Enter 不会触发提交

如果表单有一个或多个输入字段和一个或多个按钮或 input[type=submit],则在任何输入字段中按 Enter 键将触发第一个按钮或 input[type=submit] (ngClick) 上的单击处理程序,并且封闭表单上的提交处理程序 (ngSubmit)

我认为有几种方法可以修复它,但这可能是最不黑客的:

ng-click从按钮中删除处理程序,然后ng-submit在表单上使用:

<form name="myForm" ng-submit="add_new_invoice_line()">
...
<button type="submit">Add New</button>
</form>
Run Code Online (Sandbox Code Playgroud)

其他想法:

  • <form>将标签全部删除。除非你想使用 Angular 的表单验证功能。
  • 尝试在“添加新”按钮之前添加一个隐藏按钮,以便 Angular 在您按 Enter 键时找到该按钮。