What is the best way to delete a particular item from an ng-repeat list?

I'm encountering a challenge with an ng-repeat within a form.

Within my form, I have implemented a button that triggers the appearance of a set of input fields along with a remove button using ng-repeat. My objective is to allow the removal of a specific group of inputs upon clicking the designated remove button. However, as it stands, when I click the remove button, it removes the inputs from the bottom of the list regardless of where I click on the form. For clarification, refer to this GIF:

https://i.sstatic.net/qKfzY.gif

Initially, I assumed that a simple splice at the specific $index within the ng-repeat would suffice, but evidently there may be something crucial that I am overlooking.

Below is the HTML code for the ng-repeat section:

<div class="form-group">
  <label class="col-sm-2 control-label">More Parameters</label>
    <button type="button" ng-click="addParameterFields()">Add Parameter</button>
      <div class="col-sm-10 col-sm-offset-2">
        <div ng-repeat="params in formData.gameIdParams track by $index" class="controls parameters">
          <input type="text" ng-model="formData.gameIdParams.id[$index]"
            name="gameIdParamsId"
            class="col-sm-3"
            autocomplete="off"
            placeholder="Type of Input"
            validation-field-required="true"/>
          <input type="text" ng-model="formData.gameIdParams.label[$index]"
            name="gameIdLabel"
            class="col-sm-3"
            autocomplete="off"
            placeholder="Placeholder Text to add in Input Field"
            validation-field-required="true"/>
          <input type="text" ng-model="formData.gameIdParams.validationRegex[$index]"
            name="gameIdvalidationRegex"
            class="col-sm-3"
            autocomplete="off"
            placeholder="Regex used for Validation (optional)"
            validation-field-required="false"/>
          <button ng-click="formData.gameIdParams.splice($index,1)">Remove</button>
        </div>
     </div>
</div>

Furthermore, here is the logic employed for adding the forms:

$scope.addParameterFields = function() {
  console.log('CLICKED');
  if($scope.formData.gameIdParams === null || $scope.formData.gameIdParams === undefined) {
    $scope.formData.gameIdParams = [];
  }
  $scope.formData.gameIdParams.push({
    id: "",
    label: "",
    validationRegex: ""
  });
  console.log($scope.formData);
};

Thank you in advance for any assistance!

Answer №1

To efficiently manage your code, it's recommended to create a function similar to this:

ng-click="removeForm($index)"

The variable $index corresponds to the current iteration number of your ng-repeat loop.

In your controller, implement the following:

$scope.removeForm = function(index){
   delete yourObj[index];
   // or
   yourObj.splice(index, 1);
}

ACTION REQUIRED

Make sure to replace the following:

formData.gameIdParams.your_variable[$index]

With:

formData.gameIdParams[$index].your_variable

Alternatively, you can use:

params.your_variable

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 most efficient way to retrieve the largest category_id within a nested object array?

Seeking guidance as a beginner in ReactJS. I am struggling with looping through a nested object array to find the largest category Id. Despite my efforts, I am unable to retrieve the desired result because the largest category ID may not always be locate ...

Tips for launching a web application using Nuxt with Firebase

After successfully installing the Nuxt Firebase plugin into my web app, everything works flawlessly when I run the generated folder (dist) locally. However, once I deploy it to the server, my web app fails to recognize any Nuxt Firebase commands and throws ...

Trying to access a specific index in an array in react js [0] but encountering an error message "cannot read properties

https://i.sstatic.net/WZKlc.png After running the code successfully, I encounter an issue when trying to access the first index which results in an error message stating "cannot read properties of undefined (reading '0')" https://i.sstatic.net/ ...

`Turn nested JSON into a formatted list using jquery`

I am currently facing two challenges: I am having trouble with the HTML structure, as shown in the image below Current HTML structure: https://i.stack.imgur.com/GH46J.png Desired HTML structure: https://i.stack.imgur.com/Dq3Gn.png How can I create d ...

focusing on every item within a container

Currently, my code looks like this: $(".container a").css("color","#ffffff"); It styles all links inside the ".container" element to be white. However, I have a div that has the following structure: <div class="container"> <div class="header" ...

Leveraging angular's $compile for dynamic content rendering

endpointTemplate = "/api/endpoint?city={{city}}&state={{state}}&facility={{facility}}"; var model = angular.extend(scope.$new(), { city: 'Brooklyn', state: 'NY', facility: 'Facility 2' }); var compiled = $compile($(&ap ...

Angular JS throwing an error: [$injector:unpr] Provider not recognized

I am new to angular js and I'm attempting to create a custom service. I've copied and pasted some code for the custom service, but I keep encountering the following error: Error: [$injector:unpr] Unknown provider: serviceProvider <- service & ...

What is the best way to modify a particular h4 tag without impacting the rest?

Hey everyone, I'm re-uploading this post because I realized my previous explanation was unclear. I apologize for that and have deleted the old post. I am seeking to make some edits: <div id="viewer_viewer_container" style="display: block;"> ...

Unable to load images on website

I'm having trouble showing images on my website using Node.js Express and an HBS file. The image is not appearing on the webpage and I'm seeing an error message that says "GET http://localhost:3000/tempelates/P2.jpg 404 (Not Found)" Here is the ...

Utilizing Selenium TestNG: Implementing DataProvider with 1D Array to Enhance Yahoo Search Feature

When I attempted to perform a search using Yahoo search, I encountered an issue where only the first element in the array was being searched. Interestingly, the same code works fine for Google search. Here is the code snippet: package googleSearch; impor ...

jQuery Dialog interface endlessly scrolls to the top

While debugging code for a project, I came across the use of jquery UI Dialog for popups. However, there seems to be an issue where the page keeps scrolling to the top while the dialog remains stationary wherever it was opened. Below is the code snippet in ...

Creating a POST request in a C# web application

I am currently attempting to submit a form using C# After conducting some research, I have been having trouble coding it correctly (as I am new to this field). Below are the snippets of code I have: View; <form> <div class="field-wra ...

Perform the action: insert a new item into an array belonging to a model

Here is the structure of my model: var userSchema = new mongoose.Schema( { userName: {type: String, required: true}, firstName: {type: String}, lastName: {type: String}, password: {type: String, required: true}, ...

Encountering a Peer dependency problem while executing node within a docker environment

Currently, I am utilizing `node-pg-migrate`, which has a peer dependency on `pg`. Here is an excerpt from the library's `package.json` file: "peerDependencies": { "pg": "^4.3.0" }, My attempt to execute the application in Docker involves the fo ...

Replicate the function of the back button following the submission of an ajax-submitted form to Preview Form

I am currently working on a multi-part form with the following data flow: Complete the form, then SUBMIT (using ajax post) jQuery Form and CodeIgniter validation messages displayed if necessary Preview the submitted answers from the form Options: Canc ...

Display a paragraph on a webpage based on the user's response being either true or false

I am looking to create an application that consists of 3 questions, each with 2 options: yes and no. Based on the user's response, I want to display a different paragraph. How should I approach this? <!DOCTYPE html> <html> <head> ...

The result from noty.js is coming back as undefined

Recently, I started using noty.js but I encountered an issue while trying to execute the basic example for creating a noty. The error message I kept receiving was: Uncaught TypeError: Property 'noty' of object function (a,b){return new e.fn.init ...

Tips for utilizing maps in a react component within a Next.js application

I received an array of data from the backend that I need to display on a React component. home.js import Head from "next/head"; import Header from "../src/components/Header"; import * as React from 'react'; import { styled } ...

Extract particular elements from an array and transform them into a new array

Presented below is an array: [{ "title": "Apple iPhone 7 Plus 32 GB", "category": "phone", "brand": "apple", "condition": "Used", "price": 800, "id": 0, "description": "Apple" }, { "title": "Apple Ipad Air 32 GB", "category": "tablet", "brand ...

Error: Trying to use 'Player' before it has been initialized

Recently, I have been utilizing ES6 syntax along with import/export on Nodejs using the ESM module loader. Everything was running smoothly until I encountered an error related to imports. Below are the error messages that popped up: joseph@InsaneMachine ...