如何使用Angular JS处理表单中的多个提交按钮? [英] How to handle multiple submit buttons in a form using Angular JS?
问题描述
我正在使用AngularJS,我有一个用户可以输入数据的表单。在表单的最后,我想要有两个按钮,一个用于保存,它将保存并转到另一个页面,另一个按钮标记为保存并添加另一个,这将保存表单然后重置它 - 允许它们输入另一个条目。
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.
如何以角度完成此操作?我想我可以有两个带有ng-click标签的提交按钮,但我在表单元素上使用ng-submit。有什么理由我需要使用ng-submit - 我不记得为什么我开始使用它而不是按钮点击按钮。
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.
代码看起来类似于:
<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>
在控制器中 SomeController
$scope.record = {};
$scope.save = function (record) {
$http.post('/api/save', record).
success(function(data) {
// take action based off which submit button pressed
});
}
推荐答案
ngSubmit
允许您在要提交的文本框中键入时按输入
。如果该行为不重要,只需使用2 ngClick
。如果这很重要,您可以修改第二个按钮以使用 ngClick
。所以你的代码变成:
ngSubmit
allows you to press Enter
while typing on the textbox to submit. If that behavior isn't important, just use 2 ngClick
. If it is important, you can modify the second button to use ngClick
. So your code becomes:
<div ng-controller="SomeController">
<form ng-submit="save(record)">
<input type="text" name="shoppingListItem" ng-model="record.shoppingListItem">
<button type="submit">Save</button>
<button ng-click="saveAndAdd(record)">Save and Add Another</button>
</form>
</div>
这篇关于如何使用Angular JS处理表单中的多个提交按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!