本文介绍了如何在ng-repeat中使用$ error.required?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下结构:

// JS
$scope.fields = [
  { text: 'Email', type: 'text', value: '' },
  { text: 'Password', type: 'password', value: '' }
]

// HTML
<div class="user">
  <h2 class="header">Log in</h2>
  <form name="login">
    <input class="form-control" type="{{ field.type }}" placeholder="{{ field.text }}" ng-model="field.value" ng-repeat="field in fields" required />
    <a class="btn primary" href="javascript:;" ng-click="login()">Log in</a>
  </form>
</div>

如何实现如下所示的 $ error.required ? http://plnkr.co/edit/VLOEfp?p=preview

How can I implement $error.required like shown here? http://plnkr.co/edit/VLOEfp?p=preview

我不知道该放在哪里:

<div class="" ng-show="myform.routingNumber.$error.required">
  <span class="help-block">Please enter routing number</span>
</div>

也许我必须重新构造 ng-repeat ?

推荐答案

尝试以下类似方法.你快到了.只是错过了一个基本点,所有控件都需要名称.Angular使用名称进行验证.

Try something like below. You are almost there. Just missed a basic point, all controls need name. Angular uses name for validations.

<div class="user">
  <h2 class="header">Log in</h2>
  <form name="login" novalidate="">
  <div ng-repeat="field in fields" >
        <input class="form-control" type="{{ field.type }}" placeholder="{{ field.text }}" ng-model="field.value" required name="{{field.name}}"/>
        <div ng-show="login.{{field.name}}.$invalid">
          <span class="help-block">Please enter</span>
        </div>
  </div>  
    <a class="btn primary" href="javascript:;" ng-click="login()">Log in</a>
  </form>


</div>

按照如下所示在您的控制器中添加名称

Accordingly add name in your controller like below

$scope.fields = [
  { text: 'Email', type: 'text', value: '', name:'idname'},
  { text: 'Password', type: 'password', value: '', name:'password' }
]

这篇关于如何在ng-repeat中使用$ error.required?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 00:31