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
});
}
ng-submit has other advantages too. For example, invalid form will not be submitted. It is always better to use ng-submit instead of ng-click. However, in your scenario, better approach would be
Hope it helps.
ngSubmit
allows you to pressEnter
while typing on the textbox to submit. If that behavior isn't important, just use 2ngClick
. If it is important, you can modify the second button to usengClick
. So your code becomes:As I see it, you have two options: 1: Use an ngClick event on the "save and add another" button and remove the "type='submit'" portion. Then in whatever function you call gor the ngClick, you can save and then reset the values, calling save() within that function. 2: Remove the ngSubmit altogether and just use ngClicks for both buttons.
If someone looking for a simple approach then just create a flag and toggle between button and submit.
Need to handle the flag according to user action.
Make them all buttons and
type=submit
. It makes it a little cleaner not mixing and matching inputs and buttons. So basically you're trying to execute one method in your controller to handle either button click.So, in your js file you'll have something like this.
You can keep both
ng-click
andtype="submit"
. In theng-click
you can just update a parameter of your controller and validate that in the eventng-submit
:So this approach avoids you from adding a method and then calling a redundant code.
Thanks