26

考虑一个具有三个按钮的表单:

<form ng-submit="updateUser()">
  <div>Name <input type="text" ng-model="userToEdit.name" /></div>
  <div>
    <button class="btn btn-primary" ng-click="updateUser()">Save</button>
    <button class="btn" ng-click="cancelEdit()">Cancel</button>
    <button class="btn btn-danger" ng-click="deleteUser(userToEdit)"><i class="icon-trash"></i> Delete</button>
  </div>
</form>

当我单击取消时,将调用 cancelEdit(),然后调用 updateUser()。我不希望调用 updateUser() 方法。有没有办法抑制这种表单提交(最好使用 jQuery?)

注意:我仍然希望能够按 Enter 并默认为 Save 操作。

4

4 回答 4

97

There is a type attribute for the <button> which defaults to submit - see this spec. Thus every button in your form is a submit button. You need to specify the button type for buttons which should not trigger the form submission, like this:

<form ng-submit="updateUser()">
  <div>Name <input type="text" ng-model="userToEdit.name" /></div>
  <div>
    <button class="btn btn-primary">Save</button>
    <button type="button" class="btn" ng-click="cancelEdit()">Cancel</button>
    <button type="button" class="btn btn-danger" ng-click="deleteUser(userToEdit)"><i class="icon-trash"></i> Delete</button>
  </div>
</form>

And also no need to put the submit action to both ng-click and ng-submit - it will trigger double submit. I would advise to use ng-submit because it catches all ways of form submission, like pressing ENTER and not only clicking on submit button.

Hope this helps :)

于 2013-07-14T08:21:26.697 回答
13

尝试这个

<form ng-submit="updateUser()">
  <div>Name <input type="text" ng-model="userToEdit.name" /></div>
  <div>
    <button class="btn btn-primary">Save</button>
    <a class="btn" ng-click="cancelEdit()">Cancel</a>
    <a class="btn btn-danger" ng-click="deleteUser(userToEdit)"><i class="icon-trash"></i> Delete</a>
  </div>
</form>

或这个

<form>
  <div>Name <input type="text" ng-model="userToEdit.name" /></div>
  <div>
    <button class="btn btn-primary" ng-click="updateUser()">Save</button>
    <button class="btn" ng-click="cancelEdit()">Cancel</button>
    <button class="btn btn-danger" ng-click="deleteUser(userToEdit)"><i class="icon-trash"></i> Delete</button>
  </div>
</form>

最终我认为你不需要updateUser()在 html 中使用两次

于 2013-04-16T04:22:08.943 回答
6

您可以使用取消按钮类型=“重置”:

<button type="reset" class="btn" ng-click="cancelEdit()">Cancel</button>

该按钮是一个重置按钮(将表单数据重置为其初始值)

http://www.w3schools.com/tags/att_button_type.asp

于 2015-09-23T09:30:30.463 回答
1

我遇到了同样的问题。我使用锚而不是按钮。

<form ng-submit="updateUser()">
  <div>Name <input type="text" ng-model="userToEdit.name" /></div>
  <div>
    <button class="btn btn-primary" ng-click="updateUser()">Save</button>
<a class="btn btn-danger"  ng-click="cancelEdit()" role="button">Cancel</a>
    <button class="btn btn-primary" ng-click="deleteUser(userToEdit)"><i class="icon-trash"></i> Delete</button>

  </div>
</form>
于 2016-09-28T06:19:53.937 回答