How to handle multiple submit buttons in a form us

2020-06-30 05:29发布

I'm using AngularJS and I have a form where the user can enter data. At the end of the form I want to have two buttons, one to "save" which will save and go to another page, and another button labeled "save and add another" which will save the form and then reset it - allowing them to enter another entry.

How do I accomplish this in angular? I was thinking I could have two submit buttons with ng-click tags, but I'm using ng-submit on the form element. Is there any reason I NEED to be using ng-submit - I can't remember why I started using that instead of ng-click on the button.

The code looks something like:

<div ng-controller="SomeController">
    <form ng-submit="save(record)">
        <input type="text" name="shoppingListItem" ng-model="record.shoppingListItem">
        <button type="submit">Save</button>
        <button type="submit">Save and Add Another</button>
    </form>
</div>

And in the controller SomeController

$scope.record = {};
$scope.save = function (record) {
    $http.post('/api/save', record).
        success(function(data) {
            // take action based off which submit button pressed
        });
}

7条回答
贪生不怕死
2楼-- · 2020-06-30 05:56

Remove ng-submit from "form" element and define ng-click functions separately on each button with type 'submit'.For invalidation check, define name property in form element tag. And check validation in scope function.

<div ng-controller="SomeController">
<form name="saveForm">
    <input type="text" name="shoppingListItem" ng-model="record.shoppingListItem">
    <button type="submit" ng-click="save(record)">Save</button>
    <button type="submit" ng-click="saveOther(record)">Save and Add Another</button>
</form>

Scope Function:

$scope.record = {};

$scope.save = function (record) {    

if(this.saveForm.$valid)
  {

    $http.post('/api/save', record).
    success(function(data) {
        // take action based off which submit button pressed
    });
  }
}
查看更多
登录 后发表回答