Is it possible to dynamically create input fields in AngularJS by clicking a button?

I'm currently working on a project that involves adding an input field and a button each time a user clicks on the button.

Is there a way to retrieve the text from the input field when the new button, which is displayed alongside the input field, is clicked?

Check out my example on CodePen

var app = angular.module('ionicApp',['ionic']);
app.controller('cntr',function($scope){
     $scope.addfield=function(){
       alert("how to add input field dynamically")
     }

})

I'm not quite sure how to achieve this; in jQuery we can use the append function, like this:

$('.addcontend').append('<input \> <button>get input value</button>')

Can anyone guide me on how to do this using AngularJS?

Answer №1

To effectively manage the inputs, you can utilize an array to store them and iterate through the array to display them in the following manner:

<div class="addcontend">
  <div ng-repeat="item in inputs">
    <input ng-model="item.value"/> <button ng-click='addfield()'>get input value</button>
  </div>
</div>

Afterwards, initialize the inputs array and create a function to add new elements as shown below:

$scope.inputs = [];
$scope.addfield=function(){
  $scope.inputs.push({})
}

If you want to see a live demonstration, click on this link: CodePen Demo

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

Setting up Access-Control-Allow-Origin in WildFly 8.1.0 configuration

I am attempting to configure Access-Control-Allow-Origin on a Wildfly 8.1.0 server using the standalone.xml file provided below: <?xml version='1.0' encoding='UTF-8'?> <server xmlns="urn:jboss:domain:2.1"> <extensio ...

Each container has its own div counter

Help needed to complete this code. The task is to count the number of .resp-containers in each container separately. Then, based on that count, assign a corresponding class to each element within the containers. Check out the code here $(document).ready(f ...

What is causing `foo()` to function in this specific scenario?

Check out this code snippet: https://jsfiddle.net/5k10h27j/ I'm puzzled by why foo() is being called as an argument to a non-existent function. function foo(){ alert('huh??'); } jQuery('#container').on('change', ...

Issue: Module 'js' not found in Node.js Express application

I am currently working on a NodeJS express application. While developing, I encountered the following issue: Error: Cannot find module 'js' After researching online, I couldn't find a solution. The typical troubleshooting steps didn&ap ...

The body onload function fails to run upon the page loading

I'm having trouble with my body onload function not executing. When I load the page, I want to display all records that are selected in the drop_1 dropdown and equal to ALL. I have a script that sends values q and p to getuser.php. The values sent are ...

Issue detected in React Rollup: the specific module 'name' is not being exported from the node_modules directory

Currently in the process of creating a library or package from my component. The tech stack includes React, Typescript, and various other dependencies. Encountering an error while using Rollup to build the package: [!] Error: 'DisplayHint' is ...

Attempt to retrieve JSON-formatted data from a repository on Git

As a novice, I am delving into the world of ajax and experimenting with json files. Utilizing JSON formatted data is something I am keen on mastering. However, my request seems to be yielding an empty outcome. An Update: Below is the piece of code I am wor ...

Error encountered on NodeJS server

Today marks my third day of delving into the world of Angular. I've come across a section that covers making ajax calls, but I've hit a roadblock where a tutorial instructed me to run server.js. I have successfully installed both nodejs and expre ...

navigating to the start of a hyperlink

I'm having issues with scrolling to anchors and encountering 3 specific problems: If I hover over two panels and click a link to one of them, nothing happens. When I'm on section D and click on section C, it scrolls to the end of section C. ...

Move divs that are currently not visible on the screen to a new position using CSS animations

Upon entering the site, I would like certain divs to animate from an offscreen position. I came across this code snippet: $( document ).ready(function() { $('.box-wrapper').each(function(index, element) { setTimeout(function(){ ...

Getting the initial date of the upcoming month in JavaScript

I'm trying to figure out how to get the first day of the next month for a datePicker in dd/mm/yyyy format. Can anyone help? Here's the code I currently have: var now = new Date(); if (now.getMonth() == 11) { var current = new Date(now.getFu ...

AJAX - Implementing a delay in displaying AJAX results

My search function uses AJAX to retrieve data from the web-server, and I am trying to implement a fade-in animation for each search result. I want the results to load and fade in one by one with a slight delay between them. Currently, it seems like all th ...

jsonAn error occurred while attempting to access the Spotify API, which resulted

Currently, I am working on acquiring an access Token through the Client Credentials Flow in the Spotify API. Below is the code snippet that I have been using: let oAuthOptions = { url: 'https://accounts.spotify.com/api/token', method: ' ...

Exploring ways to utilize removeEventListener in React Native

Can someone assist me with converting this code to React? I am new to using React and struggling with the implementation. Thank you in advance! <progress id="bar" value="0" max="110"></progress> <button onClick={i ...

What is the importance of accessing the session object prior to the saving and setting of a cookie by Express-Session?

Quick Summary: Why is it crucial to access the session object? app.use((req, res, next) => { req.session.init = "init"; next(); }); ...in the app.js file after implementing the session middleware for it to properly function? Neglecti ...

Material UI allows for the creation of numbered lists with ease. This

<List> {instructionList.map((el) => ( <ListItem divider key={el.id}> {el.type === 'number' ? <React.Fragmen ...

A timer created using jQuery and JavaScript

Looking for a way to automatically transition between three div elements with a fade in/out effect every 8 seconds? Check out this simple code snippet I wrote: $(".link1").click(function () { $(".feature1").fadeIn(1000); $(".feature2").fadeOut(1000) ...

What is the best way to store numerous objects in an array at once?

Upon clicking the save button, I encounter this object: {description: "ghhg", dateSelected: "2020-02-27", startDate: "2020-02-27", company_id: "2", hr_id: 72, …} However, every time I click on save, a new object ...

JavaScript is restricted from being accessed beyond the confines of the ui-view element

After coming across a problem similar to one previously dismissed on stack overflow, I decided to tackle it head-on. You can find the issue and attempted solutions at this link: Previous Problem and Solutions The full project solution is available on Gith ...

The input value remains a string even after it has been converted to a float

I can't figure out where I'm going wrong. I'm attempting a simple task: getting user input, converting it to a float, and performing a calculation with that value. However, all I keep getting is NaN. Here's the input (I normally replac ...