从点击处理程序触发 angular 表单验证

Triggering angular form validation from a click handler

我有一个表单已移至 table,失去了内置的表单验证功能,因为我无法使用 ng-submit:

<tr ng-form="controller.add.form">
  <td>New item</td>
  <td><input type="text" name="name" id="newName" class="form-control" placeholder="Name" required ng-model="controller.add.name"></td>
  <td><textarea name="description" id="newDescription" class="form-control" placeholder="Description" ng-model="controller.add.description"></textarea></td>
  <td><button class="btn btn-xs btn-primary" type="submit" ng-click="controller.add.save()">Save</button></td>
</tr>

这是我的控制器的样子:

.controller('ObjectController', ['ObjectService', function(ObjectService)
{
  var objects = this;
  objects.entries = [];
  objects.add = {
    name: '',
    description: '',
    save: function()
    {
      if(!objects.add.form.$valid) return;
      ObjectService.create(
        {name: objects.add.name, description: objects.add.description},
        function(r)
        {
          if(r && 'name' in r)
          {
            objects.add.name = '';
            objects.add.description = '';
            objects.entries.push(r);
          }
        }
      );
    }
  };
  ObjectService.read({}, function(r) { objects.entries = r; });
}])

如何使保存方法在单击时使用标准弹出窗口触发验证?

来自AngularJSAPI参考:

the purpose of ngForm is to group controls, but not to be a replacement for the <form> tag with all of its capabilities (e.g. posting to the server, ...).

ngForm 允许在 主父表单 中创建 "form groups",允许单独验证组中的字段。所以你应该用 <form> 包围 ng-form 或者如果你不需要按组验证甚至丢失 ng-form 。

您需要将表单传递给您的点击处理程序。

假设您的表单名称为 "myForm",请将 ng-click 更改为:

ng-click="controller.add.save($event, myForm)"

在你的控制器中:

    save : function(event, form) {
            if (form.$invalid) {
                console.log('invalid');
            } else {
                console.log('valid');
            }
        }

刚刚注意到您关于不使用表单元素的评论 - 正如 Yaniv 所说,只需用表单元素包围 table:

<form name="myForm" novalidate>
    <table>
        <tr ng-form>
            <td>New item</td>
            <td>
                <input type="text" name="name" id="newName" class="form-control" placeholder="Name" required ng-model="controller.add.name">
            </td>
            <td>
                <textarea name="description" id="newDescription" class="form-control" placeholder="Description" ng-model="controller.add.description"></textarea>
            </td>
            <td>
                <button class="btn btn-xs btn-primary" type="submit" ng-click="controller.add.save($event, myForm)">Save</button>
            </td>
        </tr>
    </table>
</form>

演示 http://plnkr.co/edit/qKFs3q?p=preview