4

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');
    }
}
Akshay Vaghasiya
  • 1,597
  • 9
  • 36
  • 60

2 Answers2

7

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>
Disha
  • 822
  • 1
  • 10
  • 39
0

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.

  • @AnchalGupta, I know that. But there must be some solution as google team must have concerned that issue. Do you know the solution or alternate way? I have tried to recompile that div element. But still same problem. – Akshay Vaghasiya Sep 09 '16 at 07:42