Is there a way to retrieve the input element's value within the controller using ng-if?

After clicking on the submit button, I want the ng-if condition to activate in the DOM so that I can access the properties of the input element or apply a 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>

The controller code is as follows:

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

Check out this JSFiddle example: https://jsfiddle.net/f0aewhuy/. I'm encountering an error in the dev console while testing.

Any suggestions on how I could make this work?

Thanks!

Answer №1

The reason for this issue is that the ng-if directive reconstructs a section of the DOM tree based on an addInput. However, before it can be completely rendered in the DOM, it must finish the angular digest cycle, which is the process responsible for angular data binding. To ensure that the digest cycle has finished and the element is now added to the DOM, we can use $timeout like this:

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

Additionally, there is a typo here:

var inputValue = inputElement.value();

To access the value of an element, we simply need to call inputElement.value as value is a property not a function.


Live Example:

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

  <div ng-controller="myCtrl">
    <div ng-if="addInput">
      <input value="123456" id="addInput">
    </div>
    <input type="submit" ng-click="login()" value="Login">
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps should I take to host a Node.js application on a subdomain using an apache2 VPS?

Currently, I have a Node.js application that I would like to host on a subdomain using my VPS. The VPS is running apache2 and the Node.js app utilizes Express. Despite trying both Phusion and following this tutorial, I have been unsuccessful in getting i ...

Having difficulty generating a footer for a page that includes a Material-UI Drawer component

Looking to create a standard full-width footer at the bottom of my page, I need help with the implementation. Utilizing the "Permanent drawer" from Material-UI Drawer for reference here. If you're interested in experimenting with it, CodeSandbox link ...

Utilizing jQuery to Determine Character Count

I've tried everything on the site, but nothing seems to be working. I'm attempting to create a function that triggers when the character count in a div exceeds a certain number, but it's not functioning as expected. Any assistance would be g ...

Guide to populating a full calendar using JSON information

Implementing the FUllCALENDAR CSS template for creating a meeting calendar has been my current project. The servlet class I am using is CalendarController. However, when running it, the output appears as follows: {"events":[{"id":1,"title":"1","s ...

creating a loop to handle AJAX requests for JSON data

My JSON call successfully loads the data.root.offer[0].region data into a div with the class .region. Here is the code snippet: $.getJSON('json/data.json', function(data) { $('.region').html('<p>' + data.root.offer[0] ...

What is the correct way to insert a new key-value pair into an object within the state of functional components?

Is there a way to dynamically add key-value pairs to the initial state of an empty object in functional components, similar to computed property names in class components? I currently have an initial state of {}. const [choice, setChoice] = useState({}) ...

Guide for leveraging AngularJS for efficiently loading content within a collapsible panel

I'm currently working on an application that utilizes the Bootstrap Collapse component to display a series of collapsible panels, all starting in the closed position. Considering that there could be numerous panels on the page and each panel might ha ...

Issue: Module '../utils/composeObjs' not found after global installation of generator-stencil

Currently, I am in the process of developing a generator for stenciljs which can be found at https://github.com/AkashGutha/generator-stencil Within this project, there is a handy utility function located at the root directory. This function resides in one ...

How can one gain access to a specifically generated element?

In my task of dynamically generating multiple elements, I am facing an issue related to accessing specific ones. To illustrate this problem as simply as possible, I have provided the following code: $(document).ready(function() { var num1 = 0; v ...

What are the appropriate situations to utilize Q.defer versus using Promise.resolve/reject?

I've been working with nodejs and I'm curious about when to use Q defer over Promise.resolve/reject? There are numerous examples of both methods, such as: // using Q defer function oneWay(myVal) { var deferred = Q.defer(); if (myVal < 0) ...

Tips for displaying autocomplete suggestions as clickable links?

I am new to using Ajax and trying to figure out how to display autocomplete results as clickable links. I have managed to list the related results, but I am struggling to add the links. I believe the links need to be added within the script as an HTML tag. ...

The JQuery parseFloat() function seems to be consistently returning "NAN" whenever it is used with the .text property

I am currently encountering an issue with parsing the text property of an input element identified by the id currency-converter. My goal is to convert this text into a floating-point value so that I can proceed with applying mathematical operations to conv ...

Tips for changing the text in a .txt file that has been accessed through a $.get request

Is there a way to read and open a file, but update a specific value within it? For example, if my data.txt looks like: [ {"slot": "1", "name": "Bob"}, {"slot": "2", "name": "John"} ] and I want to update it with a query like: "UPDATE data.txt SET na ...

Retrieving User Activity Reports for a specified set of users within G Suite

I am currently attempting to utilize the Admin SDK Reports Service to retrieve the latest login time and other data for a specific set of 20 users. Due to the large size of the domain, it is not practical to fetch data for the entire domain and then filter ...

Loading javascript libraries that are contained within an appended SVG document

I am currently working on developing a browser-based SVG rasterizer. The unique aspect of this project is that the SVG files may contain JavaScript code that directly impacts the output, such as randomly changing element colors, and utilizes external libra ...

React JS for loop not displaying any output

I am trying to create a component that loops from 0 to the value entered as a prop. if (props.number !== "" && props.toPow !== "") { for (let i = 0; i < props.toPow; i++) { return ( <div> & ...

execute the changePage() function in jQuery using the data stored in localStorage

In my jQuery mobile page, I have a simple setup: <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.2"> <link rel="stylesheet" href="js/jquery.mobile-1.2.0.css" /> < ...

Is there a way to select a checkbox in Google Forms using the console?

I need help with a script I'm creating to automatically populate Google Forms. I am able to select checkboxes using querySelector, but they don't have a .click() method or similar. How can I go about checking the checkboxes? ...

Create a dynamic sitemap for a Laravel website that includes variables in the slugs

My Laravel-based website features URLs like this- xyz.com/search/{id}/{name} These URLs have two variables, allowing for multiple variations such as: xyz.com/search/1/katy xyz.com/search/2/john With potentially thousands of such URLs, I need to creat ...

Accents marked with diacritics are not being detected + An issue occurred while

I'm currently working on putting together a Spanish dictionary by sourcing the definitions from www.rae.es. However, there are a couple of challenges I'm facing: One issue is that the search engine does not function properly with acute accent ...