我有以下AngularJS代码,我使用ngRepeat遍历对象数组。我对数字字段进行了验证。我面临的问题是,即使一条记录的验证失败,也会抛出所有记录的错误消息。我不知道问题出在哪里。
JSFiddle Link - http://jsfiddle.net/jdev_hari/kduh4h5p/5/
控制器代码
var app = angular.module('myapp', [], function () {});
app.controller('AppController', function ($scope) {
$scope.scholarships = [
{
"name" : "abc",
"amount" : "456"
},
{
"name" : "def",
"amount" : "789"
}
];
});
HTML代码
<div ng-repeat="scholarship in scholarships">
{{scholarship.name}}
<input type="text" id="sAmount-{{$index}}" max="500" ng-model="scholarship.amount" required/>
<div ng-show="scholarship-{{$index}}.$error.max">Error</div>
</div>
输出
abc
Error
def
Error
答案 0 :(得分:1)
我修复了什么
作为评论,可能会重复How to validate inputs dynamically created using ng-repeat, ng-show (angular)
在您阅读了这个问题和答案之后,您可以理解我的答案。
HTML代码
<ul ng-repeat="scholarship in scholarships">
<ng-form name="myForm">
{{scholarship.name}}
<input type="number" name="scholarshipName" id="sAmount-{{$index}}" max="500" ng-model="scholarship.amount" style="width:100px;" required integer />
<div class="alert error" ng-show="myForm.scholarshipName.$error.max">max error</div>
</ng-form>
</ul>
JS代码
var app = angular.module('myapp', [], function () {});
app.controller('AppController', function ($scope) {
$scope.scholarships = [
{
"name" : "abc",
"amount" : 456
},
{
"name" : "def",
"amount" : "789"
}
];
});