1

when I click on the submit button ng-if condition should be enabled in DOM and I should able to access the Input element properties or I can apply some class to it

<div ng-app="myModule">

<div ng-controller="myController">
  <div ng-if="addInput">
  <input value="123456" id="addInput">

</div>
 <input type="submit" ng-click="login()" value="Login">
</div>
</div>

Controller code was

 var module = angular.module("myModule", []);

 module.controller("myController", function($scope) {


 $scope.addInput=false;

 $scope.login = function () {
   $scope.addInput = true;
  var invar= document.getElementById('addInput');
  var invalue = invar.value();
  console.log("value was " + invalue);
  };
 });

jsfiddle Example: https://jsfiddle.net/f0aewhuy/ , In dev console I'm able to see error.

How can I acheive it?

Thank you

Raj
  • 13
  • 2
  • New AngularJS developers often do not realize that `ng-repeat`, `ng-switch`, `ng-view`, `ng-include` and `ng-if` all create new child scopes, so the [data hiding] problem often shows up when these directives are involved. his issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models. – georgeawg Apr 18 '20 at 16:33

1 Answers1

0

This issue happens because the ng-if directive recreates a portion of the DOM tree based on an addInput. But, before it could be fully rendered in DOM it has to complete angular digest cycle, which is the process behind angular data binding. In order to make sure the digest cycle has fully completed and the element is now added to dom we can $timeout for this purpose like:

$scope.addInput = true;
$timeout(function() {
  var invar = document.getElementById('addInput');
  var invalue = invar.value;
  console.log("value was " + invalue);
}, 0);

Also, you have a typo here:

var invalue = invar.value();

to access an element value we simply need to call invar.value as value here is a property not a function.


Demo:

var module = angular.module("myModule", []);
module.controller("myController", function($scope, $timeout) {
  $scope.addInput = false;
  $scope.login = function() {
    $scope.addInput = true;
    $timeout(function() {
      var invar = document.getElementById('addInput');
      var invalue = invar.value;
      console.log("value was " + invalue);
    }, 0);
  };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myModule">

  <div ng-controller="myController">
    <div ng-if="addInput">
      <input value="123456" id="addInput">
    </div>
    <input type="submit" ng-click="login()" value="Login">
  </div>
</div>
palaѕн
  • 72,112
  • 17
  • 116
  • 136