验证ng-repeat:textbox和textarea中的控件

时间:2017-01-02 15:05:43

标签: angularjs angularjs-ng-repeat angularjs-validation

我正在使用Angular js,其中我有一个文本框外面和一个包含textbox和textarea的ng-repeat。我想检查单击提交按钮时字段是否包含值。我能够实现ng-repeat之外的控件功能,但不确定如何在单击提交按钮时在ng-repeat内实现必要的字段验证。以下是现有代码:

<form name="mainForm" id="createForm" ng-submit="mainForm.$valid && add()" novalidate>
        <div ng-controller="testController" ng-init="init()">    

    <div>
                        <label>Name :</label>
                    </div>
                    <div>
                        <input type="text" maxlength="150" required ng-model="testName" name="testName" />
                    </div>
                </div>
                <span style="color:red" ng-show="submitted == true && mainForm.testName.$error.required">Name is required</span>
                <br />
                <div class="row">
                    <div class="form-group ">
                        <label>Language</label>
                        <label>Title</label>
                        <label>Description</label>
                    </div>
                </div>
                <div class="row">
                    <div>
                        <div ng-repeat="Descriptions in testsWithDescription ">
                            <div>
                                <label ng-model="Descriptions.Language">{{Descriptions.Language}}</label>
                            </div>
                            <div>
                            <input type="text" maxlength="150" name="titleValidate[]" ng-model="Descriptions.Title" />
                            </div>
                            <div>
                                <textarea maxlength="500" name="descriptionValidate[]" noresize ng-model="Descriptions.Description"></textarea>
                            </div>
                            <div class="form-group col-md-1">
                                <a style="cursor:pointer"><img ng-src="{{DeleteIcon_url}}" alt="delete image" ng-click="($index == !selectedDeleteIcon) ||testsWithDescription.splice($index,1)" ng-class="{'disabled': $first}" /> </a>

                            </div>
                        </div>
                    </div>
                </div>

    <input type="submit" value="Submit" ng-click="submitted=true"/>

如何使用角度js对ng-repeat内的控件进行必要的字段验证? 感谢

1 个答案:

答案 0 :(得分:3)

您可以使用$index跟踪ng-repeat中不同输入的名称。

<div ng-repeat="Descriptions in testsWithDescription ">
     <input type="text" 
            maxlength="150" 
            name="titleValidate_{{$index}}" 
            ng-model="Descriptions.Title" 
            required />
</div>

您现在可以使用AngularJS的常用验证,就像您已经做过的那样:mainForm.$valid