AngularJS - 如何触发提交嵌套形式 [英] AngularJS - How to trigger submit in a nested form

查看:161
本文介绍了AngularJS - 如何触发提交嵌套形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要建提交时生成一个邀请的形式。邀请有几个领域,其中之一是与添加按钮,点击时要了地址添加到应该收到邀请的电子邮件地址列表的电子邮件地址输入。

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.

这可以用一个单一的形式来完成,但是如果用户点击回车键,键入电子邮件,然后它会触发提交整体形式。我想有回车键的结果 - 当电子邮件输入字段的重点是 - 作为具有点击添加按钮的效果相同。我预计,要解决这个正确的方法是将窝邀请表单内的电子邮件报名表,是这样的:

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
    }

我的问题是有嵌套的表格(和这样做从&LT转换;形式&GT; &LT; NG形式&GT; ,提交任何一个不再起作用。

My problem is that having nested the forms (and in doing so converted from <form> to <ng-form>, submitting either one no longer works.

Plunker这里

推荐答案

我有类似的规定 - 向导驱动的多步骤的形式。当用户点击下一步按钮,我已经来验证当前步骤的形式。

I've similar requirement - wizard driven multi-step form. When user clicks 'Next' button, I've to validate the current step form.

我们可以通过射击触发验证 $验证上的范围事件绑定的形式。

We can trigger validation by firing '$validate' event on the scope bound to the form.

isFormValid = function($scope, ngForm) {
    $scope.$broadcast('$validate');
    if(! ngForm.$invalid) {
      return true;
    }
}

当过我要检查,如果表单值是正确的,我会打电话给 isFormValid 的范围和放大器;形成实例。

When ever I want to check if the form values are correct, I'll call isFormValid with the scope & form instance.

工作code: Plunker链接

这也是非常有用的在 isFormValid 一些额外的逻辑的(包括在上述Plunker)的使形式和放大器;表单字段 $脏,因为我们将显示/隐藏根据验证消息的 $脏状态。

It is also useful to have few additional logic in isFormValid (included in the above Plunker) which makes the form & form fields $dirty as we would be showing/hiding validation messages based on their $dirty state.

这篇关于AngularJS - 如何触发提交嵌套形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆