【问题标题】:Check a form is valid from outside the form in another part of the DOM with Angular?使用Angular从DOM的另一部分中的表单外部检查表单是否有效?
【发布时间】:2015-09-01 17:25:46
【问题描述】:

我有一个特殊的设置,我需要在 DOM 的另一部分从表单范围之外动态显示表单是否有效。具体来说,我的标记是这样的:

<section class="overview">
  <div ng-repeat="file in files">{{ file.name }}</div>
</section>

<section class="forms">
  <form ng-repeat="file in files" name="'fileForm' + $index">
    <!-- form stuff ->
  </form>
</section>

<button>Submit All</button>

对于每个fileForm,在.overview 部分,如果相应的表单有效,我想应用ng-class。像这样的:

<div ng-repeat="file in files" ng-class="{ valid: 'fileForm' + $index.$valid }>{{ file.name }}</div>

有没有办法使用 Angular 的原生表单工具来实现这一点?

【问题讨论】:

    标签: javascript html angularjs forms


    【解决方案1】:

    是的,表单状态对象以从表单名称派生的属性插入到您的范围/控制器中。

    <section class="overview">
      <div ng-repeat="file in example.files">
        <div ng-class="{'file-invalid': example.fileForms[$index].$invalid}">
          File item "{{ file.name }}" is valid: {{example.fileForms[$index].$valid}}</div>
        </div>
    </section>
    
    <section class="forms">
      <form ng-repeat="file in example.files" 
      name="{{'example.fileForms.' + $index}}">
    
        <input ng-model="file.name" required>
    
      </form>
    </section>
    

    简单的例子在这里http://plnkr.co/edit/7LMLDi?p=preview

    为了舒适的工作,最好将 ng-form 用于内部表单,将 form element 用于外部。如果内部形式之一无效,则外部形式自动无效。例子在这里http://plnkr.co/edit/9m94AuNMR8J077Cakvgb

    【讨论】:

      猜你喜欢
      • 2019-06-13
      • 2017-12-10
      • 2012-10-08
      • 2021-02-16
      • 1970-01-01
      • 2019-02-06
      • 2017-11-03
      • 1970-01-01
      • 2020-08-03
      相关资源
      最近更新 更多