ng-required not working as expected if parent div is hidden conditionally

Issue

In my code I am using ng-show and ng-required in combination. But, ng-required is not working as expected even when the respective $scope variable value is set to false. Please find the code below

<div role="form" name="selectQuestionsForm" id="selectQuestionsForm" ng-form>
    <div class="form-group col-sm-12">
        <label  class="control-label question-answer-label"
                  for="firstQuestionSelect">First question</label>

        <div>
            <select class="form-control nopadding">
                <option value="">-- Select --</option>
            </select>
        </div>
        <div ng-show="showCustomQuestion.first" >
            <input type="text" class="form-control" ng-model="questionsText.first" ng-required="showCustomQuestion.first"
            id="firstQuestionInput" name="firstQuestionInput" validation-min-length="3" validation-max-length="100" />
        </div>
        <label  class="control-label question-answer-label"
                  for="firstAnswerInput">First answer</label>
        <div style="padding-bottom: 15px;">
            <input type="text" class="form-control" ng-model="answersText.first" 
            id="firstAnswerInput" validation-min-length="3" validation-field-required="true" validation-max-length="100" required/>
        </div>
    </div>
</div>
<div id="securityActionBtnContainer" class="visible-md visible-sm visible-lg">
    <button id="saveBtn" type="button" ng-disabled="selectQuestionsForm.$invalid" class="btn btn-default btn-xs pull-right"  ng-click="saveQuestion(selectQuestionsForm.$valid)">Save</button>
    <button id="cancelBtn" type="button" class="btn btn-xs btn-default pull-right" style="margin-right: 10px;" ng-click="redirect['cancel']()">Cancel</button>
</div>

The select element have a logic to display the option and it is working fine. When we select the option ‘Write my own question’, the hidden input is displayed. If user choose any other question the custom question input is hidden and not part of the form element. But ng-required is still getting applied though the value is set to the false and respective form doesn’t validate.

Please let me know what I am missing to make it work. Thanks in advance for your help.

Solution

Use ng-if instead of ng-show. Items hidden using ngShow or ngHide still exist in the DOM and will be processed by angular. It’s just not visible to a user.

Answered By – HankScorpio

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.