Recording the $index value of dynamically included inputs

Check out my Plunker demo:

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

I have a dynamic set of form elements that users can add and remove. I am looking to include an 'id' property for each object in the form elements, corresponding to their index position.

For example, the current structure is:

[ { "Selection": "", "Text": "" }, { "Selection": "", "Text": "" } ]

I want it to be structured like this:

[ { "Selection": "", "Text": "", "Id" : "1" }, { "Selection": "", "Text": "", Id : "2" } ]

This is the controller code snippet:

 function DuplicateInputCtrl($scope) {
      $scope.foodTypes = [
        {
          "code" : "AP",
          "type" : "Apple"
        },
        {
          "code" : "CH",
          "type" : "Chicken"
        },
        {
          "code" : "GR",
          "type" : "Grape"
        }
      ]

      $scope.foods = [
        {
          "Selection": "",
          "Text": ""
        }
      ]

      $scope.cloneItem = function () {
        var itemToClone = { "Selection": "", "Text": "" };
        $scope.foods.push(itemToClone);
      }

      $scope.removeItem = function (item) {
        $scope.foods.splice(item, 1);
      }

      $scope.saveForm = function () {
        console.log($scope.foods);
      }

This is the HTML code snippet:

 <body ng-controller="DuplicateInputCtrl" class="container">
  <div data-ng-repeat="food in foods">
  <div class="form-group title-field">
    <label for="">Food {{ $index + 1 }}</label>
    <select class="form-control input-full" data-ng-model="food.Selection"
        data-ng-options="foodType.code as foodType.type for foodType in foodTypes">
        <option value="">Select</option>
    </select>
    <input type="hidden">
    <button data-ng-click="removeItem($index)" class="btn delete-field-{{$index}}">
      Delete
    </button>
  </div>
  <div class="form-group">
      <textarea class="form-control" data-ng-model="food.Text"></textarea>
  </div>
</div>
<button data-ng-click="cloneItem()" class="btn inline">
  Add
</button>

<div>
  <button class="btn btn-medium" ng-click="saveForm()">Save</button>
</div>


{{ foods | json }}

</body>

Answer №1

Check out the example using $watchCollection here

  $scope.$watchCollection('foods', function() {
    angular.forEach($scope.foods, function(x, i) {
      x.id = i;
    });
  });

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 is the best way to initiate a re-render after updating state within useEffect()?

I'm currently strategizing the structure of my code using React hooks in the following manner: Implementing a state variable to indicate whether my app is loading results or not The loading state turns to true when useEffect() executes to retrieve da ...

Tips for effectively handling numerous events from multiple Slickgrid instances on a single page

I'm encountering an issue with utilizing multiple Slickgrids on a single page. With the number of grids changing dynamically, I generate them within a JavaScript function and maintain them in a grid array as shown below. var columns = []; var options ...

Experiencing difficulties when trying to pan and zoom the data obtained from d3.json within a line chart

I am currently working on developing a trend component that can zoom and pan into data fetched using d3.json. Here is the code I have written so far: <script> var margin = { top: 20, right: 80, bottom: 20, left: 50 }, width = $("#trendc ...

It appears that Promise.all is not adequately ensuring that all tasks are completed before moving on

In my current project, I am trying to achieve a complex cycle where an HTTP GET request is executed to fetch data, followed by the creation of multiple "subrequests" based on that data. The goal is to ensure that the next iteration of the cycle begins only ...

What is the best way to include key-value pairs in a jQuery array?

I am facing an issue with a group of checkboxes. I need to add the values of these checkboxes, each containing a pair of numbers, to an array and then use them. However, the problem is that the array only takes the value of the last checkbox. Despite my ef ...

Error! The function worker.recognize(...).progress is throwing an error. Any ideas on how to resolve this

Here is the code snippet: //Imports const express = require('express'); const app = express(); const fs = require("fs"); const multer = require('multer'); const { createWorker } = require("tesseract.js"); co ...

Retrieving Information from Ajax Response Following a Successful Insert Query in Codeigniter

I am trying to use ajax method to insert form data into a database and then redirect it to the next page. I have successfully passed the data in ajax and inserted it into the database table. However, I am facing an issue with getting the generated referenc ...

The state variable remains undefined even after integrating useEffect in a React.js component

Hello, I have a component within my React application that looks like this: import React, { useEffect, useState } from "react"; import AsyncSelect from "react-select/async"; import { ColourOption, colourOptions } from "./docs/data"; const App = () => ...

Executing a post request asynchronously and storing the retrieved data into a variable

Currently, I am in the process of learning AngularJS and attempting to upgrade my current method of fetching data from a web service and dynamically assigning it to a variable that is binded using ng-repeat. My main objective is to implement an asynchronou ...

The function of window.location is a mixed bag of success and failure

I am encountering an issue with a JavaScript function that is supposed to navigate to the next page when clicking a button. The function works correctly for step 1, but it fails for step 2. Upon executing the function using nextstep = 'form', _b ...

Having trouble getting ng-repeat to work properly alongside Bootstrap collapse?

Using a bootstrap 4 card to create a blog post. When the View Comments link is clicked, a collapsed div within the card-footer should open to display all comments. The collapse functioned correctly with hard coded html and dynamic data {{blog.title}} until ...

Utilize esbuild to monitor for any modifications, recompile the code, and automatically restart the express server

In my endeavor to develop a basic SSR-powered project using express + react, I find the need to monitor frontend and backend scripts concurrently in the development process. The primary objective is to utilize express routes in directing to react page com ...

Error: Unable to access the 'clearAsyncValidators' property as it is undefined when running Jest tests on an Angular component

Encountering an Error While Testing Components with Jest Here is my code block for onClickLogin() method: onClickLogin() { if(this.loginForm.valid) { this.api.getLoginData().subscribe(res => { const user = res.find(a => { ...

JavaScript and CSS tabs with smooth transition effect

I want to create tabs that smoothly fade between each other when switching. The code I have works, but there's a slight issue. When transitioning from one tab to the previous one, there is a momentary glitch where the last tab briefly changes state be ...

Enhancing the capabilities of a browser detection function in Javascript

Looking to enhance my Javascript browser detection function with input from others. Concerns: The assumption that "Chrome 18" is equivalent to "Maxthon 3" may not be accurate! How can we distinguish between Chrome 18 and Maxthon 3? Similarly, how can we ...

Presentation - hyperlink only functioning for final slide

I have a question about Lean Slider, which you can check out at My goal is to link each slide to a different URL. However, I'm facing an issue where only the code in the last slide seems to be executed and applied to all other slides. For example, if ...

What is the impact of util.inherits on the prototype chain in JavaScript?

Exploring this particular design: Function ConstrA () { EventEmitter.call(this); } util.inherits(ConstrA, EventEmitter); var obj = new ConstrA(); If util.inherits is omitted, ConstrA and obj will each establish their own distinct prototype chain. T ...

What is the best way to deactivate the first two columns of the header in Vue?

I am attempting to deactivate the draggable function for the first 2 columns. I have tried using options in the draggable plugin. :options="{disabled : 'Subject'}" However, this disables the draggable functionality for all headers. < ...

Using Jquery to toggle columns based on their index and custom attribute

My table has two rows in the header: the first row with colspan and the second row containing headers. You can see an image below for reference. With a jQuery function, I extract all the table cell values from the second header row and add them to a div w ...

Refrain from revealing AngularJS code before activating it

My AngularJS code displays every time I reload the page Issue: The code appears even when my internet connection is slow or the page does not fully reload. I only want it to display the result. I would appreciate any suggestions for a solution. Thank you ...