Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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');
    }
}
like image 224
Akshay Vaghasiya Avatar asked Mar 12 '23 04:03

Akshay Vaghasiya


1 Answers

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>
like image 194
Disha Avatar answered Apr 26 '23 13:04

Disha