我有以下结构:
// 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
我不知道放在哪里:
<div class="" ng-show="myform.routingNumber.$error.required">
<span class="help-block">Please enter routing number</span>
</div>
也许我必须重新组织ng-repeat
?
答案 0 :(得分:1)
尝试以下内容。你快到了。只是错过了一个基本点,所有控件都需要名称。 Angular使用名称进行验证。
<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>
相应地在控制器中添加名称,如下所示
$scope.fields = [
{ text: 'Email', type: 'text', value: '', name:'idname'},
{ text: 'Password', type: 'password', value: '', name:'password' }
]
答案 1 :(得分:1)
在示例代码中,myform.routingNumber.$error.required
myform
是表单的名称(html属性),routingNumber
是应该验证的输入元素的名称。
所以,就像这样,
<form name="myform">
<input name="routingNumber" ng-model="myRoute" />
<div class="" ng-show="myform.routingNumber.$error.required">
<span class="help-block">Please enter routing number</span>
</div>
</form>
在您的代码上实现此功能
因此,在您的实际代码中(使用ng-repeat
),您必须为每个输入元素创建一个唯一的名称。
<div class="user">
<h2 class="header">Log in</h2>
<form name="login">
<input class="form-control" name="{{field.text}}" type="{{ field.type }}" placeholder="{{ field.text }}" ng-model="field.value" ng-repeat-start="field in fields" required />
<div ng-repeat-end class="" ng-show="myform[field.text].$error.required">
<span class="help-block">Please enter {{field.text}}</span>
</div>
<a class="btn primary" href="javascript:;" ng-click="login()">Log in</a>
</form>
</div>
答案 2 :(得分:1)
即使@Naga Sandeep回答了这个问题。我只是添加另一个条件来包装错误消息,否则即使用户没有触摸表单也会显示错误消息。
<div ng-app="myApp", ng-controller="myCtrl">
<form name="myForm" novalidate="">
<div ng-repeat="info in loginInfo">
<input type="{{info.type}}" ng-model="info.value" name="{{info.name}}" required novalidate>
<span ng-show="myForm.{{info.name}}.$touched || myForm.$submitted">
<span ng-show="myForm.{{info.name}}.$invalid">Please enter this field</span>
</span>
</div>
<button type="submit">
Login
</button>
</form>
</div>
angular.module("myApp", [])
.controller("myCtrl", myCtrl);
function myCtrl($scope){
$scope.loginInfo = [
{"name": "user_email", "value": "", "type":"email"},
{"name": "user_pass", "value": "", "type":"password"}
]
}