输入填充动态时,AngularJS表单验证失败 [英] AngularJS form validation failing when input populated dynamic

查看:141
本文介绍了输入填充动态时,AngularJS表单验证失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下表格:

如果单击星号,则输入内容将自动被单击的星号填充. (单击第三颗星,输入将像下面的图所示那样填充数字"3")

I have the following form:

If I click on a star, the input will be automatically populated with the number of the clicked star. (clicking on the 3rd star the input will be populated with number '3' like in the image bellow)


输入星号的下方是ng-required="true".


The input bellow the stars is ng-required="true".

<form name="completeSurveyForm" role="form" novalidate ng-submit="vm.save()">
    <ul class="question-list">
        <li data-ng-repeat="question in vm.survey.questions | orderBy:'conditionalOrderId' track by question.id ">
            <small class="label label-primary pull-right">{{question.questionTypeName}}</small>
            <h3>
                <b>{{$index +1 }}.</b>&nbsp;{{question.questionBody}}
            </h3>
            <hr> <!-- Replace here with directives -->
            <div data-ng-switch="question.questionType">
                <numericrange question="question" data-ng-switch-when="NUMERIC_CHOICE" />
            </div>
        </li>
    </ul>
    <button type="submit" ng-disabled="completeSurveyForm.$invalid " class="btn btn-primary">
        <span data-translate="fqApp.business.form.submit">Submit</span>
    </button>
</form>

numericalrange指令如下所示:

And the numericrange directive looks like this:

<div class="row">
    <div class="col-md-2" ng-if="!completed">
        <div>
            <span ng-mouseover="showHovered($event)" ng-mouseleave="clearStars($event)" ng-click="selectStar($event)"
                data-ng-repeat="sym in range(startNonActive(question), question.maxValue, 1)" class="{{question.symbol}} starred-element" value="{{$index}}">
            </span>

            <input type="number" name="{{question.id}}"
                   data-ng-model="question.numericValue"
                   data-ng-value="numberOfSelectedStars" ng-required="true" />
        </div>

    </div>
</div>

解决问题:

如果我单击星号,并且输入内容会动态填充一个数字,那么表单将无法进行验证,如下图所示:

If I click on a star and the input populates dynamically with a number the form fails to validate like in the image bellow:

我在输入中手动输入一个数字,该数字是有效的,并且我可以单击提交按钮.

I manually write a number in the input the form is valid and I can click the submit button.

但是,如果为什么我在输入中手动输入数字,则该表格将变为有效,并且我可以单击提交"按钮,并且如果通过选择星号自动填充了输入,则该表格将无效并且我无法单击提交"按钮?

推荐答案

当您单击星号时,在分配值时手动使其变脏.

While you clicking on star, manually make dirty when value assigned.

angular.forEach($scope.form.$error.required, function(field) {
    field.$setDirty();
})

您可以使用$setViewValue(value, trigger)方法.当控件要更改视图值时,将调用此方法. 请在此处

You can use $setViewValue(value, trigger) method. This method will be called when a control wants to change the view value. Refer here

这篇关于输入填充动态时,AngularJS表单验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆