Cannot read property '$valid' of undefined if form is inside a div with ng-if condition

ぐ巨炮叔叔 提交于 2019-12-10 18:53:13

问题


I have a form inside a div with ng-if condition. Initially form is closed. On click a button, form is displayed. But on submitting form, I'm getting Cannot read property '$valid' of undefined error. If I change ng-if into ng-show, it works perfect. But I must have to use ng-if. I can't find reason of error. And one more thing that, on getting error, I'm also getting form object as null. If any one knows the answer, it will be appreciated.

Here is my code

HTML

<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');
    }
}

回答1:


Pass the form in addComment - fiddle

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



回答2:


ng-if condition doesn't add the components into the DOM until condition is satisfied whereas the ng-show add the the component in DOM and when condition is satisfied, it displays. So ,that's the reason it is giving error as it is not available on the DOM.



来源:https://stackoverflow.com/questions/39405645/cannot-read-property-valid-of-undefined-if-form-is-inside-a-div-with-ng-if-co

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