AngularJS - 如何在嵌套表单中触发提交 [英] AngularJS - How to trigger submit in a nested form
问题描述
我正在构建一个在提交时生成邀请的表单.邀请有多个字段,其中一个是带有添加"按钮的电子邮件地址输入,点击该按钮后,应将该地址添加到应接收邀请的电子邮件地址列表中.
I'm building a form that generates an invitation when submitted. The invitation has several fields, one of which is an email address input with an 'add' button, which when clicked should add that address to a list of email addresses that should receive the invite.
这可以通过单个表单完成,但是如果用户在输入电子邮件时按下 Enter 键,则会在整个表单上触发 submit
.我希望输入键结果 - 当电子邮件输入字段被聚焦时 - 与单击添加"按钮具有相同的效果.我希望解决这个问题的正确方法是在邀请表中嵌套一个电子邮件输入表,如下所示:
This can be done with a single form, however if the user hits the enter key while typing an email then it triggers submit
on the whole form. I'd like to have the enter key result - when the email input field is focused - have the same effect as clicking the 'add' button. I expected that the proper way to solve this would be to nest an email entry form within the invitation form, something like this:
<ng-form ng-submit="sendInvite()">
<input type="text" placeholder="Title" ng-model="invitation.title"/>
<ng-form ng-submit="addInvitee()">
<input type="email" placeholder="Title" ng-model="inviteeEmail"/>
<button class="btn" type="submit">add</button>
</ng-form>
<button class="btn" type="submit">Send</button>
</ng-form>
在控制器中使用以下 javascript:
With the following javascript in the controller:
$scope.addInvitee = function() {
$scope.invitation.emails.push($scope.inviteeEmail);
$scope.inviteeEmail = '';
}
$scope.sendInvite = function() {
//code to send out the invitation
}
我的问题是嵌套表单(并在这样做时从 转换为
,提交任何一个都不再有效.
My problem is that having nested the forms (and in doing so converted from <form>
to <ng-form>
, submitting either one no longer works.
推荐答案
您可以使用以下两种方式之一来指定提交表单时应调用的javascript方法:
* 表单元素上的 ngSubmit 指令
* ngClick 指令在第一个按钮或提交类型的输入字段上 (input[type=submit])
-- 表单文档
<ng-form>
<input type="text" placeholder="Title" ng-model="invitation.title"><br>
<ng-form>
<input type="email" placeholder="Title" ng-model="inviteeEmail">
<button class="btn" ng-click="addInvitee()">add</button><br>
</ng-form>
<ul class="unstyled">
<li ng-repeat="invitee in invitation.invitees">
<span>{{invitee.email}}</span>
</li>
</ul>
<button class="btn" ng-click="sendInvite()">Send</button>
</ng-form>
这篇关于AngularJS - 如何在嵌套表单中触发提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!