AngularJS - ngRepeat - 所有元素的错误消息

时间:2015-06-02 23:05:54

标签: angularjs

我有以下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

1 个答案:

答案 0 :(得分:1)

我修复了什么

  1. 使用ng-form - HTML
  2. &#34;数字&#34;的输入类型不是&#34;文字&#34; - HTML
  3. 命名输入 - HTML
  4. 将金额字符串修改为数字 - JS
  5. 作为评论,可能会重复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"
            }  
        ];
    });