【问题标题】:Validate controls within ng-repeat: textbox and textarea验证 ng-repeat 中的控件:文本框和文本区域
【发布时间】:2017-01-02 15:05:43
【问题描述】:

我正在使用 Angular js,其中我有一个外部文本框和一个包含文本框和文本区域的 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"/>

如何使用 Angular js 对 ng-repeat 中的控件使用必填字段验证? 谢谢

【问题讨论】:

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


    【解决方案1】:

    您可以使用$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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-04
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      • 2016-08-29
      • 2011-12-25
      • 1970-01-01
      相关资源
      最近更新 更多