访问重复之外的ng重复ng形式

Access ng-repeat ng-form outside of the repeat

本文关键字:ng 重复 形式 访问      更新时间:2023-09-26

我有一个按钮和一个表。如果任何一行无效,我想禁用该按钮。我该如何做到这一点?

///// This doesn't work, I have no access to myForm /////
<button ng-disabled="myForm.$invalid">Save</button>
<table>
  <tr ng-repeat="item in items" ng-form="myForm">
    <td>
      <input type="text" name="description" value="{{value.description}}" />
    </td>
  </tr>
</table>

编辑:将整个表格包装成一个表格,结果如下:http://pasteboard.co/FJccNeg.png

您需要多种东西:

  • 具有表单标记以便启用验证。使用novalidate属性禁用broswer默认验证
  • 每个输入只使用一个名称,为此,我们将使用ng repeat提供的$index,以便每个输入都有自己的验证
  • 在下面的示例中添加一些可能触发验证错误的内容。我添加了必需的属性。因此,只要至少有一个字段为空,该按钮就会被禁用

angular.module("app", []).controller("ctrl", function($scope){
    $scope.items=[{description:"toto"},{}];//on with already existing one with empty
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app"> 
    <form name="myForm" ng-controller="ctrl" novalidate><!-- mandatory -->
    <button ng-disabled="myForm.$invalid">Save</button>
    
    <table>
      <tr ng-repeat="item in items" ng-form="myForm">
        <td>
          <input type="text" name="{{'description'+$index}}" ng-model="item.description" required/>
        </td>
      </tr>
    </table>
    </form>
  </div>

首先,您应该定义一个带有name参数的表单,然后创建带有name paramaeter的输入字段。然后,您可以使用表单名称和输入名称参数来访问输入的错误。

    <form name="myForm" ng-controller="FormController" class="my-form">
          userType: <input name="input" ng-model="userType" required>
          <span class="error" ng-show="myForm.input.$error.required">Required!</span><br> > 
         <button ng-disabled="myForm.input.$error.required>"
        </form>

我不知道你对每一行的表单做了什么,但为了在表单无效时停用按钮,你必须将按钮包装在表单中:

<form name="myForm">
  <input name="description" type="text" ng-model="description" required />
  <button ng-disabled="myForm.$invalid">Save</button>
</form>

如果你不能把你的按钮放在这个表格里,那么你不能使用角度魔法,所以使用它没有多大意义只有一半。

在你的控制器里有一组输入ng模型,检查所有模型是否有效,然后设置一个值true/false来停用你的按钮。