Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs model value is undefined in form

I have two forms(in one page). On first form there are two buttons NEXT and BACK. On clicking on the next i will render next form on page. I am using ng-if for this condition.

<form name="otpform" novalidate ng-if="renderotpform">
  <fieldset ng-disabled="otpdisable">
    <div class="middle-container steps fourth-step overflow-hidden" id="divotp">
      <input class="" type="text" name="otp" placeholder="{{ 'OTP' | translate }}" ng-model="otp" required >
      <input type="button" value="{{ 'BACK' | translate }}" class="brown-button" ng-click="gotoAck()">
      <input type="submit" value="{{ 'NEXT' | translate }}" class="blue-button" ng-click="checkotp()">
    </div>
  </fieldset>
</form>

Below is my js code.

 $scope.checkotp = function () {
                debugger;
                var otpvalue;
                $scope.otp = {};
                otpvalue = $scope.otp; //undefined
              }

When I try to access the otp model I am getting undefined property. On previous form I have next button. Inside next button I have $scope.renderotpform = true; so that above form is shown. May I know why I am not able to access OTP in the above code?

like image 439
Niranjan Godbole Avatar asked Feb 26 '26 08:02

Niranjan Godbole


1 Answers

ng-if creates its own scope. So the otp inside ng-if is not binded directly to the controller.You can either bind the model to an object or use controller as syntax. The controller as syntax implicitly takes care of the dot rule.

For more info:

  1. https://github.com/angular/angular.js/wiki/Understanding-Scopes
  2. AngularJs "controller as" syntax - clarification?

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  var vm=this;
  vm.renderotpform = true;
  vm.checkotp = function() {
    console.log(vm.otp);
  }
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl as vm">
    <form name="otpform" novalidate ng-if="vm.renderotpform">
      <fieldset ng-disabled="otpdisable">
        <div class="middle-container steps fourth-step overflow-hidden" id="divotp">
          <input class="" type="text" name="otp"  ng-model="vm.otp" required>
          <input type="button" value="BACK" class="brown-button" ng-click="vm.gotoAck()">
          <input type="submit" value="NEXT" class="blue-button" ng-click="vm.checkotp()">
        </div>
      </fieldset>
    </form>
  </div>
like image 172
Vivz Avatar answered Feb 28 '26 00:02

Vivz