我有一个动态表单,它是从某些api收到的数据生成的,你可以看到它的例子here,收到的数据是这样的:
$scope.users = [
{
name: 'one',
email: 'one@one.com'
},
{
name: '',
email: 'two@two.com'
},
{
name: '',
email: 'three@three.com'
}
];
我为这些项目创建了一个动态表单,但我遇到的问题是我的验证消息没有正确显示,它们与此类似:
<form name="usersForm">
<div ng-form="subForm" ng-repeat="user in users">
<input name="name" type="text" ng-model="user.name" required />
<p ng-if="subForm.name.$invalid && subForm.name.$touched">
name is required
</p>
<input name="email" type="email" ng-model="user.email" required />
<p ng-if="subForm.email.$invalid && subForm.email.$touched">
email is required
</p>
</div>
</form>
正如你在plunkr中看到的那样,我使用了两种方法来实现这一点,一种是使用ng-form
而另一种是使用插值形式输入名称:
<form name="usersForm2">
<div ng-repeat="user in users track by $index">
<input name="name{{$index}}" type="text" ng-model="user.name" required />
<p ng-if="usersForm2['name' + $index].$invalid && usersForm2['name' + $index].$touched">
name is required
</p>
<input name="email" type="email" ng-model="user.email" required />
<p ng-if="usersForm2['email' + $index].$invalid && usersForm2['email' + $index].$touched">
email is required
</p>
</div>
</form>
如何向用户显示验证消息(加载或呈现表单时)?
答案 0 :(得分:2)
查看更新的plunker或运行以下代码
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.users = [
{
name: 'one',
email: 'one@one.com'
},
{
name: '',
email: 'two@two.com'
},
{
name: '',
email: 'three@three.com'
}
];
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link href="style.css" rel="stylesheet" />
<script src="https://code.angularjs.org/1.5.4/angular.js"></script>
<!-- By setting the version to snapshot (available for all modules), you can test with the latest master version -->
<!--<script src="https://code.angularjs.org/snapshot/angular.js"></script>-->
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div>
First approach using ng-form
</div>
<form name="usersForm">
<div ng-form="subForm" ng-repeat="user in users">
<input name="name" type="text" ng-model="user.name" required />
<p ng-if="subForm.name.$invalid && subForm.name.$error">
name is required
</p>
<input name="email" type="email" ng-model="user.email" required />
<p ng-if="subForm.email.$invalid && subForm.email.$error">
email is required
</p>
</div>
</form>
<div>
second approach using interpolation
</div>
<form name="usersForm2">
<div ng-repeat="user in users track by $index">
<input name="name{{$index}}" type="text" ng-model="user.name" required />
<p ng-if="usersForm2['name' + $index].$invalid && usersForm2['name' + $index].$error">
name is required
</p>
<input name="email" type="email" ng-model="user.email" required />
<p ng-if="usersForm2['email' + $index].$invalid && usersForm2['email' + $index].$error">
email is required
</p>
</div>
</form>
</body>
</html>