AngularJS form validation failing when input populated dynamic

[亡魂溺海] 提交于 2019-12-08 03:58:05

问题


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)


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>

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>

Getting into the problem:

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.

But why If I write manually a number in the input, the form gets valid and I can click the 'submit' button and if the input is populated automatically by selecting a star, the form does not validate and I cannot click on the 'submit' button?


回答1:


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

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

or

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



来源:https://stackoverflow.com/questions/44668289/angularjs-form-validation-failing-when-input-populated-dynamic

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