简体   繁体   中英

AngularJS form validation failing when input populated dynamic

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM