【问题标题】:ng-required not working as expected if parent div is hidden conditionally如果有条件地隐藏父 div,则 ng-required 无法按预期工作
【发布时间】:2015-09-03 17:21:53
【问题描述】:

在我的代码中,我将ng-showng-required 结合使用。但是,ng-required 无法按预期工作,即使相应的$scope 变量值设置为false。请在下面找到代码

<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>

select 元素具有显示选项的逻辑,并且工作正常。当我们选择“写我自己的问题”选项时,将显示隐藏的input。如果用户选择任何其他问题,自定义问题 input 将被隐藏,而不是表单元素的一部分。但是ng-required 仍然被应用,尽管值设置为false 并且相应的form 不验证。

请让我知道我缺少什么以使其正常工作。提前感谢您的帮助。

【问题讨论】:

  • ng-show 采用表达式,但 ng-required 采用布尔值。你知道showCustomQuestion.first的价值吗?你是如何在你的控制器中改变它的?

标签: angularjs requiredfieldvalidator ng-show angularjs-validation angularjs-forms


【解决方案1】:

使用ng-if 代替ng-show。使用 ngShow 或 ngHide 隐藏的项目仍然存在于 DOM 中,并将由 angular 处理。它只是对用户不可见。

【讨论】:

    猜你喜欢
    • 2021-02-27
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多