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

Encountering an issue while attempting to import JSON data into an Angular component

Looking to create a straightforward photo gallery using angularJs. The goal is to pull images from a json file and showcase them on the view file. The idea is that once a tab is clicked, the corresponding images should be displayed. Controller $scope.loa ...

What is the mechanism behind property binding in Angular 2? Can you explain what is happening in this specific scenario?

Being a novice in the realm of Angular 2, I find myself grappling with doubts related to property binding. While this particular example seems to work fine, I can't help but wonder about what exactly goes on behind the scenes. Within my component vi ...

The POST request from the form is returning a null value

I am currently facing an issue with using post in Express and BodyParser to insert data from a form in an EJS file into MySQL. The data keeps returning null, indicating that it is not being parsed correctly from the form to the backend. Can anyone offer as ...

Tips for concealing the sorting number in the grid header

I have implemented angularjs ui-grid for sorting 4 columns in my grid. However, I want to hide the sort numbers displayed in the grid. I have searched for a solution or configuration through API but did not find anything helpful. Thank you. https://i.sta ...

Issue with Vue3: The imported module is not defined

Update: I recently downgraded vue-cli to version 4.5.19 and now the code is functioning properly. It seems like there might be an issue related to vue-cli or its dependencies. I encountered a problem while working on a simple vue.js project using vue-cli. ...

The button's background color remains the same even after clicking on it

In my exploration of Vue.js, I decided to create a simple project to grasp the concept of class binding. I wanted to add functionality to each button component, so that when a button is clicked, it would change its color or background color to something ot ...

Exploring the power of Express.js by utilizing local variables and rendering dynamic views

I am in the final stages of completing an application using node.js and express, even though I am still relatively new to them. Here's my situation: In my app.js file, I have declared a variable app.locals.webLang and set its initial value to "EN". T ...

Exploring the functionality of the load event in JQuery for images

I am encountering an issue with the code provided below: <!DOCTYPE html> <html> <head> <style> </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </hea ...

Unexpected behavior: JQuery Ajax request not displaying Json object following recent update to JQuery version 1.10.2

Currently facing an issue with a project I am working on. The previous programmer used jquery 1.4.4, and I have updated it to 1.10.2 due to the designer using Bootstrap. However, after running it in version 1.10.2, one of the objects that was functional i ...

What is the procedure for re-executing the request handler in a Node.js and Express application?

Currently, my setup involves node, express, and mongojs. Here is a code snippet that exemplifies my configuration: function mongoCallback(req, res) { "use strict"; return function (err, o) { if (err) { res.send(500, err.message); } else ...

Creating an empty array of objects in Vue 3 requires using the Vue 3 syntax

In my project using Vue3 with Nuxt, I encountered an issue. My goal is to initialize an empty array of objects and then populate it. let results = ref([]); results.value = [ { "name": input.value, } ...

Make the checkbox font-weight bold when it is checked

Attempting to apply custom CSS to enhance the appearance of checkboxes using input and label elements. The goal is to make the font-weight bold when a user clicks on the checkbox, and then revert it back to regular if clicked again. Currently stuck on this ...

I'm having trouble getting my button to work with addEventListener while using Ejs and Express. What could

Creating a Twitter-like platform where I can post tweets and have them display on the same page has been quite challenging. I've set up each post to have an Edit button initially hidden with 'display:none'. However, when I try to click on th ...

Tips for choosing a single checkbox from a set of multiple checkboxes in React.js

I iterated through a list of objects to generate table rows, each containing an input tag with the type set as checkbox. const [ isChecked, setIsChecked ] = useState(false); const handleChange = (e) => { setIsChecked(e.target.checked) ...

Determine the value of a field by utilizing the values of two other fields through an onChange event

Setting the Stage: Imagine a scenario with 3 key fields: quantity, singlePrice, and totalPrice. I want these fields to be part of my form, with totalPrice being dynamically recalculated whenever quantity or singlePrice changes. My Approach: I created ...

What could be causing the model to not bind correctly in nodejs?

In the process of developing a web app with nodejs, angular, and mongo, I have encountered a strange issue. The model is not binding properly from the JSON object. Here is my Schema: var mongoose = require('mongoose'); var productSchema = new ...

Evaluating the compatibility of AngularJS using the Selenium testing

I am currently working on a single-page application using ASP MVC and AngularJS, and I am looking for ways to test the UI. Right now, I am experimenting with Selenium along with PhantomJS and WebKit drivers. On one of my testing pages, there is a list of ...

I'm curious about the potential vulnerabilities that could arise from using a Secret key as configuration in an express-session

Our code involves passing an object with a secret key's value directly in the following manner --> app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: { secure: true } }) I am pondering wheth ...

having difficulty sending the username and password from the HTML page to the controller in AngularJS

In my AngularJS controller, I am having trouble retrieving the values of the username and password fields after submitting the login form. Here is the HTML code for the form: <form class="form-signin" action="" method="post"> ...

The XORS error appears when using Angular $http, but $ajax from jQuery works fine

As the title suggests, I'm facing an issue with my code. The first part where I make a $http call is giving me a cross-domain error. However, the second part using jQuery ajax call works perfectly and returns an array of data. Can anyone shed some li ...