0

我在 angularjs 中使用表单验证,但我遇到了与此 Google 群组线程相同的问题:https ://groups.google.com/forum/#!msg/angular/W1Yya5TfIWo/7jZbfL-wROUJ,为空在用户输入值之前,表单会向用户“大喊”。

$dirty为了解决这个问题,我只在字段为(已被用户触摸)时显示错误消息。但是,如果用户直接提交表单而不接触任何内容,则不会提交表单(因为它不是$valid),但它也不会显示任何错误消息(因为字段不是$dirty)。

然后建议在先前链接的 Google Groups 线程中“触摸”无效表单提交上的字段。我使用以下方法执行此操作:

$scope._updateUntouchedFields = function(form) {
  for(var f in form) {
    var field = form[f];

    if (field.$addControl !== undefined) {
      // $addControl exists, this is a nested form
      // recursively update fields in that form
      $scope._updateUntouchedFields(field);
    } else if (field.$setViewValue !== undefined) {
      // $setViewValue exists, this is a field, just
      // set the view value to the current view value
      if(field.$dirty) continue;
      field.$setViewValue(field.$viewValue);
    }
  }
};

如果表单在提交时无效,则调用上述函数。我有两个问题:

  1. 我如何确定当前表单控件是否为嵌套表单似乎有点像 hack。有没有更好的,更像棱角分明的方式?理想情况下,我想要一个所有表单控件的列表,无论它们是否嵌套在其他表单中。
  2. 这可以以某种方式自动完成吗?有没有办法覆盖表单指令,或者可能将指令添加到<form>我可以放置此功能的标签?就像现在一样,我需要在我有表单的每个控制器中都有它,并将逻辑添加到提交函数中。
4

0 回答 0