无法读取未定义的属性"$valid",如果表单位于具有 ng-if 条件的 div 内



我有一个表单内的div与ng-if条件。最初形式是封闭的。单击按钮,将显示表单。但在提交表单时,我得到了Cannot read property '$valid' of undefined错误。如果我将ng-if更改为ng-show,它可以完美地工作。但我必须用n -if。我找不到出错的原因。还有一点,在获取错误时,我还会得到form object为null。如果有人知道答案,我将不胜感激。

我的代码

<div id="addCommentDiv" ng-if="showAddCommentForm == true">
    <form id="formAddComment" name="formAddComment" novalidate>
        <textarea id="taAddComment" name="taAddComment" placeholder="Add a comment.." ng-model="new_comment" ng-maxlength="1000" ng-required="true"></textarea>
        <button type="button" ng-click="addComment()" ng-disabled="addCommentDisabled">Ok</button>
    </form>
</div>

JS

$scope.addCommentDisabled = false;
$scope.addComment = function () {
    if ($scope.formAddComment.$valid) {
        console.log('valid');
    }
}

在addComment -中传递表单小提琴

$scope.addComment = function (formAddComment) {
 console.log('valid');
 if (formAddComment.$valid) {
    console.log('valid');
 }
}
 <button type="button" ng-click="addComment(formAddComment)" ng-disabled="addCommentDisabled">Ok</button>

ng-if condition在条件满足之前不会将组件添加到DOM中,而ng-show会将组件添加到DOM中,并在条件满足时显示。所以,这就是它给出错误的原因因为它在DOM上不可用

最新更新