Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS - Cancel button on form suppress form submission

Tags:

angularjs

Consider a form with three buttons:

<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> 

When I click cancel, cancelEdit() is being called, then updateUser() is being called. I don't want the updateUser() method to be called. Is there a way to suppress this form submission (preferebly wtihout jQuery?)

Note: I'd still like to be able to hit enter and default to the Save action.

like image 401
Dave Avatar asked Apr 16 '13 04:04

Dave


2 Answers

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 :)

like image 118
Shimon Rachlenko Avatar answered Oct 11 '22 18:10

Shimon Rachlenko


Try this

<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> 

or this

<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> 

ultimately I don't think you need updateUser() twice in the html

like image 28
Fresheyeball Avatar answered Oct 11 '22 18:10

Fresheyeball