0

I have the following AngularJS code, where I loop through the object array using ngRepeat. I have a validation for the numeric field. The issue that I face is that, even if one record's validation fail, the error message is thrown for all records. I am not sure where is the issue.

JSFiddle Link - http://jsfiddle.net/jdev_hari/kduh4h5p/5/

Controller Code

var app = angular.module('myapp', [], function () {});

app.controller('AppController', function ($scope) {    
    $scope.scholarships = [
        {
            "name" : "abc",
            "amount" : "456"
        },
        {
            "name" : "def",
            "amount" : "789"
        }
    ];
});

HTML Code

<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>

Output

abc  
Error

def  
Error
Hari
  • 117
  • 2
  • 15
  • 1
    Check your console for error. also the validation object will not be populated without using a form. Also `max` does not work with input type text. You may want to use number type. Your html is also invalid – PSL Jun 02 '15 at 23:12
  • 1
    possible duplicate of [How to validate inputs dynamically created using ng-repeat, ng-show (angular)](http://stackoverflow.com/questions/12044277/how-to-validate-inputs-dynamically-created-using-ng-repeat-ng-show-angular) – Marko Jun 02 '15 at 23:31

1 Answers1

1

What I fix

  1. Use ng-form - HTML
  2. Input type for "number" not "text" - HTML
  3. Named input - HTML
  4. Fix amount string to number - JS

As a comment, It may possible duplicate of How to validate inputs dynamically created using ng-repeat, ng-show (angular)

After you read that question and answers, you may understand my answer.

HTML Code

<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 Code

var app = angular.module('myapp', [], function () {});

app.controller('AppController', function ($scope) {    
    $scope.scholarships = [
        {
            "name" : "abc",
            "amount" : 456
        },
        {
            "name" : "def",
            "amount" : "789"
        }  
    ];
});
Community
  • 1
  • 1
Oh Seung Kwon
  • 431
  • 3
  • 11