Expanding form fields dynamically with AngularJS

I am currently working on a form that allows users to click a '+' sign in order to add new lines. I've set up a function to be called when the button is clicked, which should push a new line into the array. However, for some reason the new lines are not being created successfully. On the other hand, the function responsible for removing a line seems to be functioning properly.

Take a look at the JavaScript code below:

var myApp = angular.module('myApp', []);

myApp.controller('myController', ['$scope', '$q', function($scope, $q) {
    $scope.arr = [1,2];
    $scope.addLine = function(index){
        $scope.arr.push();
    }
    $scope.removeLine = function(index){
        $scope.arr.splice(index, 1);
    }
}]);

Answer №1

Make sure to push an element into the array.

The Purpose of push() and How to Use It: By utilizing the push() method, you can append new elements to the end of an array and receive the updated length as a result.

Please Note: Newly added items will be placed at the end of the existing array.

Additionally, keep in mind that this method alters the array's length.

Pro Tip: When you need to insert items at the start of an array, employ the unshift() method instead.

http://www.w3schools.com/jsref/jsref_push.asp

var myApp = angular.module('myApp', []);

myApp.controller('myController', ['$scope',
  function($scope) {

    $scope.arr = [1, 2];
    $scope.addLine = function(index) {
      $scope.arr.push(index);
    }
    $scope.removeLine = function(index) {
      $scope.arr.splice(index, 1);
    }
  }
]);
<!doctype html>
<html ng-app="myApp">

<head>
  <title>Hello AngularJS</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>

<body>
  <div ng-controller="myController">
    <button name="addLine" ng-click="addLine(arr.length+1)">Add Line</button>
    {{ arr | json}}

    <ul>
      <li data-ng-repeat="x in arr">
        {{ x }}  - <button name="addLine" ng-click="removeLine($index)">Remove Line</button>
      </li>
    </ul>

  </div>
</body>

</html>

Answer №2

Take a look at this:

var app = angular.module('App', []);

app.controller('AppController', ['$scope', function($scope) {
    $scope.arr = [1,2];
    $scope.addLine = function(last){
        $scope.arr.push(last + 1);
    }
    $scope.removeLine = function(index){
        $scope.arr.splice(index, 1);
    }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" ng-controller="AppController">
    <button ng-click="addLine(arr.length)">Add Line</button>
    <hr/>
    <div data-ng-repeat="x in arr">
        Line: {{x}} <button ng-click="removeLine($index)">Del</button>
    </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

Route in Node.js for event binding

Currently, I am using expressjs in combination with nowjs and binding some events to the now object directly within the route when it is accessed. However, this approach feels messy and I am concerned that every time the route is accessed, the events are e ...

Deciphering JSON using JavaScript

Looking to decode a URL using Javascript? let url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=London&destinations=drove&mode=driving&language=en&sensor=false"; fetch(url) .then(response => response.json()) .th ...

The bundle.js file is displaying HTML code instead of JavaScript

I have been working on setting up redux server-side rendering using express.js. Most of the setup is done, but I encountered an error while trying to render the page in the browser. The error message Uncaught SyntaxError: Unexpected token < is appearin ...

What is the best way to display the nested information from products.productId?

How do I display the title and img of each product under the product.productId and show it in a table? I attempted to store the recent transaction in another state and map it, but it only displayed the most recent one. How can I save the projected informa ...

Can you explain the purpose of the .json() function in Angular2?

Can you explain the purpose of the .json() function within http requests in Angular2? Here is an example code snippet: this.http.get('http://localhost:8080/getName') .subscribe(res => this.names = res.json()); Is it correct to assume that t ...

Guide to fetching external data with Next.js and importing the component into a different file

I have implemented the following code in my pages/github file, and when I navigate to localhost:3000/github, the code runs successfully and returns JSON data. function GithubAPI(props) { // Display posts... return (<div>{props.data.name}</div& ...

Can JavaScript be used to create a CSRF token and PHP to check its validity?

For my PHP projects, I have implemented a CSRF token generation system where the token is stored in the session and then compared with the $_POST['token'] request. Now, I need to replicate this functionality for GitHub Pages. While I have found a ...

Using the .each method in AJAX JQUERY to iterate through callback JSON data and applying an if statement with Regular Expression to identify matches

Implementing a live search feature using ajax and jQuery involves running a PHP script that returns an array of database rows, encoded with JSON, based on the textfield input. This array is then iterated through in JavaScript after the callback function. ...

Guide to adding an image with feathers.js and multer:

I am currently working on integrating feathers.js with React for my project and I am facing an issue with uploading images. I have tried using multer and busboy for handling the upload, but I am unable to successfully upload the image or access it through ...

Get the XML element containing the desired value in the downloadURL

Seeking assistance from experienced individuals regarding XML usage. Admitting to my lack of knowledge in this area, I am a beginner and seeking patience. I have successfully implemented code that loads marker data from a MySQL database and displays it on ...

The concept of asynchronicity and callbacks in JavaScript

As a newcomer to the world of JavaScript and Stack Overflow, I have been learning about synchronous, asynchronous, and callbacks through various videos and blogs. However, I still have a lingering doubt. If synchronous code means following a sequential ord ...

Remove an item from an array in JavaScript by specifying its value, with compatibility for IE8

Is there a way to remove an item from an array by its value rather than index, while ensuring compatibility with IE8? Any assistance would be greatly appreciated. Thank you. Below is the array in question: var myArray = ['one', 'two', ...

Using Selenium Webdriver to target and trigger an onclick event through a CSS selector on a flight booking

I've been running an automation test on the website . When searching for a flight, I encountered an issue where I was unable to click on a particular flight. I initially tried using Xpath but it wasn't able to locate the element when it was at th ...

The parseFloat function only considers numbers before the decimal point and disregards

I need my function to properly format a number or string into a decimal number with X amount of digits after the decimal point. The issue I'm facing is that when I pass 3.0004 to my function, it returns 3. After reviewing the documentation, I realized ...

Creating a 2D array matrix in JavaScript using a for loop and seamlessly continuing the number count onto the next row

I'm attempting to create a 2d matrix with numbers that continue onto the next row. var myMatrix = []; var rows = 5; var columns = 3; for (var i = 0; i < rows; i++) { var temp = 1; myMatrix[i] = [i]; for (var j = 0; j < columns; j++) ...

Uncovering components generated by React JS with BeautifulSoup

My goal is to extract anchor links with the class "_1UoZlX" from the search results on a specific page - After analyzing the page, I realized that the search results are dynamically generated by React JS and not readily available in the page source or HTM ...

What methods can I use to minimize the duration of invoking the location.reload() function?

When I'm using window.location.reload() in my onClick() function, it's taking too long to reload. I tried modifying the reload call to window.location.reload(true) to prevent caching, but it's still slow. The issue seems to be with location. ...

Parsing JSON sub items in Android application using Java

Here is a snippet of my PHP file: <?php $myObj = array( "name"=>"John" , "age"=>"30" , "post"=>[ "title"=>"What is WordPress" , "excerpt"=>"WordPress is a popular blogging platform" , ...

Error: The first certificate could not be verified, although I included rejectUnauthorized: false option

I have encountered an issue with my getServerSideProps() function, as it is throwing an error when trying to call an external API: FetchError: request to https://nginx/api/items failed, reason: unable to verify the first certificate The self-signed cert ...

"Using a WMD Editor to show the content of the wmd-preview division and questions on how to save this content in a

I am currently in the process of integrating the WMD editor into my website. Everything seems to be functioning correctly so far, but I have hit a roadblock: How can I store the entered information in my database? I have developed a JS/Ajax function that a ...