4

I'm having difficulty getting the validation to work using an ng-repeat statement. I have the following code. I just want the has-error to be added to the div.form-group when the name field is empty. I cant seem to get it work. Any thoughts?

My Attempt in fiddler

<div ng-app="app" ng-controller="bookController">
    <form name="myForm" ng-submit="submitMe(this)" novalidate>
        <table class="table">
            <tr ng-repeat="order in orders">
                <ng-form name="innerForm">
                <td>{{ order.id }}</td>
                <td>
                    <div class="form-group" ng-class="{ 'has-error' : innerForm.name.$invalid && submitted }">
                        <input type="input" ng-model="order.name" name="name" required />
                    </div>
                </td>
                </ng-form>
            </tr>
        </table>
        <input type="submit" value="submit" ng-click="submitted = true" />
    </form>

    <pre>
        {{ orders | json }}
    </pre>

</div>


var app = angular.module("app", []);

app.controller("bookController", function ($scope) {

    $scope.submitMe = function(form) {
        console.log(form);
    };

    $scope.orders = [{
        id: 1,
        name: ''
    }, {
        id: 2,
        name: 'hat'
    }];

});
Mantisimo
  • 4,203
  • 5
  • 37
  • 55
  • Is there a reason for the nested ng-form? – Jonathan Palumbo Mar 25 '14 at 18:45
  • 1
    Because you can't dynamically generate the "name" attribute of form input elements, which he needs for validation http://docs.angularjs.org/api/ng/directive/form. see also http://stackoverflow.com/questions/12044277/how-to-validate-inputs-dynamically-created-using-ng-repeat-ng-show-angular – jbll Mar 25 '14 at 18:51

1 Answers1

8

Move the ngForm directive to the element that contains the ngRepeat directive:

<tr ng-repeat="order in orders" ng-form="innerForm">

Demo: http://jsfiddle.net/YTR95/

tasseKATT
  • 38,470
  • 8
  • 84
  • 65
  • In Angular 1.3.15, I cannot get this to work. ng-form is not picking up the parent form when used this way. I've used it to success before but within a table, this doesn't work. – Alex White Jun 04 '15 at 22:40