Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs: Form inside ng-if not accessible from controller

I have a form inside ng-if directive. I want to check the form validation in controller using $valid.

    <div ng-if="paymentMethod == 12">
    <form name="creditForm" id="cc-form" novalidate>
        <div class="form-group">
            <label for="cardNumber">Card Number</label>
            <input type="text" autofocus class="form-control" name="card_number" ng-minlength="16" id="cardNumber" ng-model="creditCardNumber" required>
            <div class="red-text" ng-messages="creditForm.card_number.$error" ng-if="creditForm.card_number.$dirty || creditForm.$submitted">
                <div ng-message="required">##global.Card_Num_Required##</div>
                <div ng-message="maxlength">##global.Card_Num_MinLength##</div>
                <div ng-message="minlength">##global.Card_Num_MaxLength##</div>
                <div ng-message="minlength">##global.Card_Num_Numeric ##</div>
            </div>
        </div>

and trying to check valid form in controller

  if ($scope.$parent.creditForm.$valid) { 
      alert('valid');
      } else {
     alert('not valid');
 }

but the form is not accessible from controller.

like image 562
monda Avatar asked Nov 17 '16 07:11

monda


2 Answers

The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM. you can go throgh this link doc and also my answer here answer

You can use ng-show instead of ng-if if its feasible to you.

like image 108
Disha Avatar answered Oct 17 '22 09:10

Disha


It works fine when you use auxiliary object in your controller.

In Your Controller file

$scope.page = {
    creditForm:null
};

in your HTML file

<div ng-if="paymentMethod == 12">
<ng-form name="page.creditForm" id="cc-form" novalidate>
    <div class="form-group">
        <label for="cardNumber">Card Number</label>
        <input type="text" autofocus class="form-control" name="card_number" ng-minlength="16" id="cardNumber" ng-model="creditCardNumber" required>
        <div class="red-text" ng-messages="page.creditForm.card_number.$error" ng-if="page.creditForm.card_number.$dirty || page.creditForm.$submitted">
            <div ng-message="required">##global.Card_Num_Required##</div>
            <div ng-message="maxlength">##global.Card_Num_MinLength##</div>
            <div ng-message="minlength">##global.Card_Num_MaxLength##</div>
            <div ng-message="minlength">##global.Card_Num_Numeric ##</div>
        </div>
    </div>
</ng-form>

in this model you can saftly use ng-form inside ng-if

like image 3
user1856096 Avatar answered Oct 17 '22 10:10

user1856096