Angular validation in an ng-repeat not working

久未见 提交于 2019-12-10 17:07:09

问题


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'
    }];

});

回答1:


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/



来源:https://stackoverflow.com/questions/22642536/angular-validation-in-an-ng-repeat-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!