Add the item and increase its value within an array using AngularJS

http://plnkr.co/edit/NDTgTaTO1xT7bLS1FALN?p=preview

<button ng-click="addRow()">add row</button>

<div ng-repeat="row in rows">
<input type="text" placeholder="name"><input type="tel" placeholder="tel">
</div>

I am currently facing an issue while trying to add new rows and saving the fields. I need help with figuring out how to determine the current number of rows and incrementing to push into the array.

Answer №1

Check out this unique demonstration I designed that enables the creation of up to eight distinct input fields for Telephone and Text Entries.

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

app.controller("MyCtrl", function($scope) {
$scope.rows = [];
  
var Row = function(tel, text) {
  // Private data
  var private = {
    tel: tel,
    text: text
  }

  // Expose public API
  return {
    get: function( prop ) {
      if ( private.hasOwnProperty( prop ) ) {
        return private[ prop ];
      }
    }
  }
};

  $scope.addRow = function(){
    
    if($scope.rows.length < 8){
      var newItemNum = $scope.rows.length + 1;
      var row = new Row('item' + newItemNum, 'item' + newItemNum);
      
      $scope.rows.push(row);
    }
  };
  
  $scope.saveAll = function(){
  //  $scope.result = 'something';
  };

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp">
<div ng-controller="MyCtrl">

      <h2>Setting</h2>
      <button ng-click="addRow()">Add Row</button>
      <br />
    
      <div ng-repeat="row in rows">
        <input type="text" placeholder="Text" ng-model="row.textModel" >
        <input type="tel" placeholder="Phone" ng-model="row.telModel" >
      </div>
    
      <br />
      {{rows}}
</div>
</div>

Answer №2

Transfer the functions to be housed within controller 'Ctrl'.

Within your script:

function Ctrl($scope) {
    $scope.result = "something";
    $scope.rows = ['1'];

    $scope.addRow = function(){
        if ($scope.rows.length < 8) {
            $scope.rows.push($scope.rows.length + 1);
        }
    }

    $scope.saveAll = function(){
    //  $scope.result = 'something';
    }
}

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

Perform activities within a component responsible for displaying a flatlist

I have a component called Post that I'm using to display posts within a FlatList. Currently, the Post component only shows text and images in the Flatlist. However, within the Post component, there are buttons that should have functionality such as de ...

combining input fields for editing as a single unit instead of individually

Current Situation : At the moment, I have a form where individual records of input fields such as firstName, lastName, and email can be edited and saved without any errors. Requirement : However, I now want to be able to edit and save the firstName and ...

Need to monitor a Firebase table for any updates

How can I ensure my Angular 2 app listens to changes in a Firebase table? I am using Angular2, Firebase, and TypeScript, but the listener is not firing when the database table is updated. I want the listener to always trigger whenever there are updates or ...

Looking to retrieve data using Cheerio? If you're finding that the data appears empty in the page source but is visible when inspecting the elements, here's how you can go

I am encountering difficulties while trying to scrape data from another website. In my case, I notice that the data appears empty when viewing the page source, but it is visible when inspecting the elements. If you're confused, please refer to the fol ...

A Complication Arises with Browser Functionality When Embedding an Iframe within

I am experiencing a peculiar problem while embedding an iframe with a specific src inside an absolutely positioned div. Here's the basic structure of the webpage: .container { position: relative; overflow: hidden; width: 100%; heigh ...

Issue with angularjs ui.router delaying the rendering of ui-view

I've been working on implementing ui-router in my project. Here is the core module setup: var core = angular.module('muhamo.core', ['angular-loading-bar', 'anguFixedHeaderTable', 'ui.router']); For the tra ...

Deactivate input areas while choosing an option from a dropdown menu in HTML

I've been working on creating a form and have everything set up so far. However, I'm looking to disable certain fields when selecting an option from a dropdown list. For instance, if the "within company" option is selected for my transaction typ ...

Designing a file upload progress bar with the help of jquery and ajax

I am looking to implement a progress bar for uploading files utilizing jquery and ajax. Here is the jquery code I have written: function updateProgress(evt) { // evt is an ProgressEvent. if (evt.lengthComputable) { var percentLoaded = ...

Connecting an HTML box to a JavaScript function for the desired outcome: How to do it?

My goal is to connect the input box with id="b" (located inside the div with id="but1") with a JavaScript function that calculates values within an array. Although my junior logic review didn't detect any issues in the code, what mistakes could I have ...

Error Encountered: Unhandled Runtime Error in Next.js with Firebase - TypeError: Unable to access the property 'initializeApp' as it is undefined

It's baffling why this error keeps appearing... my suspicion is directed towards this particular file. Specifically, firebaseAuth={getAuth(app)} might be the culprit. Preceding that, const app = initializeApp(firebaseConfig); is declared in "../f ...

What is the best way to incorporate my CSS file into an HTML file when using Express?

When I try to host my html file using Express, it seems that my CSS is not getting applied. Why is this happening and what is the best way to include my CSS file with Express? const express = require('express'); const bodyParser = require('b ...

My React app experienced a severe crash when trying to render an animation in L

Currently, I am working on a React application that was set up using Vite. I recently incorporated an animation using Lottie, and although I was successful in implementing it, I encountered a problem when navigating between different pages of my applicati ...

Is it possible to save round items within a session?

While utilizing Blocktrail's API for bitcoin wallet management, I encountered an issue with circular references within the returned wallet object. The goal is to store the decrypted wallet in the user's session to avoid password re-entry. Howeve ...

Building a DOM element using jQuery

I have a function $(document).ready(function () { $("#btnhighlight").click(function () { var htext = $("#txthighlighttext").val(); $("#lstCodelist option").each(function () { var sp = $(this).text(); ...

Obtaining the TemplateRef from any HTML Element in Angular 2

I am in need of dynamically loading a component into an HTML element that could be located anywhere inside the app component. My approach involves utilizing the TemplateRef as a parameter for the ViewContainerRef.createEmbeddedView(templateRef) method to ...

Tips for eliminating repetitive code in JavaScript

I have a jQuery function that deals with elements containing a prefix 'receive' in their class or ID names. Now, I need to duplicate this function for elements with the prefix 'send'. Currently, it looks like this: function onSelectAddr ...

Incorporating arguments within the context of a "for each" loop

I'm attempting to develop a straightforward script that converts RGB-16 colors to RGB-8. The script is functioning properly, but I'm having trouble converting it into a function that can handle two different palettes. Whenever I try using palette ...

apply styling to the placeholder with CSS

I have been attempting to customize the styling of the placeholder text. After setting the color to red within the input class, I did not see any changes. Even after conducting research and referring to this link Styling the placeholder in a TextField, I w ...

Executing Scripts within the Browser: A Guide to Using Selenium

One of my current objectives involves running a script on my Selenium browser that establishes a variable and then using DevTools to access this variable in the console log. Below is the conflicting script that I am encountering issues with: from selenium ...

Angular's import and export functions are essential features that allow modules

Currently, I am working on a complex Angular project that consists of multiple components. One specific scenario involves an exported `const` object in a .ts file which is then imported into two separate components. export const topology = { "topolo ...