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

Issue

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

Solution

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>

Answered By – Disha

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.