How to add a second or additional array to an array object in AngularJS

angular.module('print', []).
controller('Ctrl', function($scope) {
  $scope.settingData = [{
    "currency": "RM",
    "fields": {
      "type": "",
      "cost": "",
      "pax": "1"
    }
  }]

  $scope.addNewFields = function() {
    var row = $scope.settingData.length;
    if (row < 3) {
      $scope.settingData.push(row);
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>

<div ng-app="print" ng-controller="Ctrl ">
  <button ng-click="addNewFields()">Add</button>
  <br />
  <br />
  <div class="editSection">
    <div class="inputRowWrap" ng-repeat="data in settingData">
      {{data.fields.type}} {{data.fields.cost}} {{data.fields.pax}}
      <div class="row">
        <div class="col col-40">
          <label class="item item-input">
            <input type="text" placeholder="Room Type #{{$index+1}}" ng-model="data.fields.type">
          </label>
        </div>
        <div class="col col-40">
          <label class="item item-input">
            <input type="text" placeholder="RM" ng-model="data.fields.cost">
          </label>
        </div>
        <div class="col">
          <select ng-model="data.fields.pax">
            <option>pax</option>
            <option value="1">1 pax</option>
            <option value="2">2 pax</option>
          </select>
        </div>
      </div>
    </div>
    <div class="padding saveBtnWrap">
      <button ng-click="saveSetting()">Save</button>
    </div>
  </div>
</div>

I implemented a feature to dynamically add new HTML elements, however, I encountered an issue where the new input fields were not functioning as expected. It seems that my attempt to add a new array object to the existing array object was unsuccessful.

Answer №1

if (row < 3) {
    $scope.settingData.push(row);
}

An integer is being added to an array of objects. Check out the edited fiddle: https://jsfiddle.net/mkcegb80/1/

Answer №2

It is important to push an object into the array instead of pushing the index.

angular.module('print', []).
controller('Ctrl', function($scope) {
  var data = {
    "currency": "RM",
    "fields": {
      "type": "",
      "cost": "",
      "pax": "1"
    }
  }

  $scope.settingData = [angular.copy(data)]

  $scope.addNewFields = function() {
    var row = $scope.settingData.length;
    if (row < 3) {
      // make a copy of the data object and add it to the array
      $scope.settingData.push(angular.copy(data));
    }
  }
});

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

Tips for updating and inserting dynamically generated form textbox values into a MySQL database

In my PHP project, I have a MySQL DB with a bunch of features table. I retrieve the data using PHP and create a table with textboxes named after column names and record IDs in the photos table using the following code: functions.php Code: function m_html ...

JSON file not found by the system

I am currently working on a basic program that consists of 3 files: 1. An HTML file named index.html 2. A JavaScript file named app.js 3. A JSON dataset called dataset.json I am struggling to make the browser recognize the data in my program. This is ...

Issue with getStaticProps not updating fetched values in Next.js production environment

I am currently working on building a blog using Next.js. Since the back-end is taken care of by another team, I am utilizing fetch API calls in getStaticProps to retrieve my articles, even though it may be considered best practice to interact with the data ...

Functional Component causing React Native's Siri Dictation to be interrupted by excessive re-renders

I'm currently working on a React Native project and facing an issue with input handling. Whenever I use Siri dictation from the iOS keyboard, the words get cut short due to a rerendering process. Although I found a similar question on Stack Overflow ...

Obtain the information from a JSONP-formatted dataset

Just when I think I have mastered identifying an element in an object, I come across a situation where I am unable to obtain the desired value. This part is successful and the data returned is accurate: A map click triggers the function MapClick(queryResu ...

Sending data via req.body from middleware

One middleware function is defined as follows: app.use('api/', authenticate, bar); In the authenticate function, a variable is being attached to req.body like so: req.body.user = foo; However, when trying to access req.body.user inside the ba ...

Bash Array Looping in a for statement

Is this the correct way to print out elements from the 13th element up until the second-to-last element of an array in BASH, even if I don't know the length of the array? for index in `seq 13 $(({myarray[@]-1))` do echo ${myarray[index]} done ...

Leveraging the div id attribute in an HTML element

As a newcomer to front-end development, I am currently working with Angular Material. I am attempting to access a specific div element from a parent HTML file. Here is what I am trying to achieve: div.html <div id="myDiv"> <h1>My work in ...

Struggling to update the inner HTML of a <p> tag using LocaleDateString() function

Recently, I've been experimenting with creating a calendar but encountered a frustrating issue. I created a variable storing a date using the toLocaleDateString method. However, when attempting to modify a paragraph's inner HTML, nothing seemed t ...

An issue with the THREE.js TextureLoader not functioning properly when deployed

After implementing the code below, my project is successfully rendering my background and avatar. However, when deploying on Netlify, the rendering does not function as expected. I have attempted using "../../", "./", and other variations, but the issue p ...

Utilize Windows Phone to Encode NFC Tag

I am currently working on writing and reading NFC tags using the ProximityDevice class on Windows Phone 8.1. Here is the code snippet I'm using to write the tag... var dataWriter = new Windows.Storage.Streams.DataWriter(); dataWriter.unicodeEncoding ...

Can multiple objects be grouped together and easily dragged in Leaflet?

Is there a way to group a set of objects together so they can be dragged simultaneously? I want to make multiple objects draggable on a map and have them behave as a single marker when moved. Currently, I have a geojson file containing several objects that ...

Retrieve the IDs of list elements in order to dynamically update a div using AJAX

I'm facing a bit of a challenge at the moment. I have a webpage that uses jQuery to load three different views: one displaying all categories associated with the user, another showing the image and name of items within the selected category, and a thi ...

Issue encountered while compiling all handlebars templates into a single JavaScript file

Below is the structure of my folders: app └───templates ├───templ1.hbs ├───templ2.hbs └───templ3.hbs I am looking to compile (precompile) all templN.hbs handlebars template files into one templ.js file. However ...

Nuxt project encountering issues with loading JS files

I've been integrating a bootstrap template into my Nuxt project but seem to be facing some challenges with loading the necessary scripts. I've attempted to import the scripts into my nuxt.config.js file in a couple of ways: 1.) Initially, I tri ...

Can you please guide me on how to convert pug (jade) to html using npm scripts?

Struggling to construct my package.json file, I find myself facing a challenge when it comes to writing scripts. "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build-css":"node-sass --output-style compressed -o bu ...

Using the native functionality, submitting a razor form with JQuery AJAX in MVC6

Is there a specific method to submit a form using jQuery AJAX in MVC6 while still utilizing the Auto Binding functionality of ASP.NET MVC? In previous versions of MVC, one could use jquery.unobtrusive-ajax and simply utilize @using (Ajax.BeginForm("SaveDa ...

What is the process behind Express and React Routes when the browser sends an initial GET request?

Embarking on my journey into the realm of React and full-stack development, I find myself in need of guidance on a particular issue that has been eluding me. In my quest to create an app using React and Express, authentication plays a crucial role. My pla ...

What is the best way to trigger a function in my JavaScript code when the console log is opened on my webpage?

I have a requirement to hide the username and password fields in a form from being viewed in the console log. My plan is to listen for the console log event and then remove the values from these fields using jQuery. Any tips on how to achieve this? Thank ...

Stay put, conceal, and revert selected option according to the button

Apologies for the confusion with the title of this section. I want to hide certain select options until a user selects a specific button. Once a button is selected, I want the corresponding select field to remain visible. However, if the user chooses a di ...