Is there a way to delete objects that are added dynamically to an array using a specific button linked to each object?

I am currently using Angular to develop a shopping list application. To facilitate testing, I have set up two pre-made lists with two and three pre-defined items each. However, the goal is for users to dynamically add both items and lists themselves in the future. I have successfully implemented an "Add Item" button that allows users to append new items to each list.

Feel free to experiment with the functionality by accessing this CodePen - http://codepen.io/anon/pen/WraZEv

<body ng-controller="notepadController as notepad">
    <header ng-repeat="list in notepad.lists">
        <div>Delete list</div>
        <h1>{{list.name}}</h1>
    </header>
    <div ng-repeat="list in notepad.lists" class="shoppingList" ng-controller="ItemController as itemCtrl">
        <ul>
            <li ng-repeat="item in list.items">
                <label>
                    <input type="checkbox" ng-model="item.checked">
                    {{item.name}}
                </label>
                <form name="removeItemForm" ng-submit="itemCtrl.removeItem(list)">
                    <input type="submit" value="Remove Item">
                </form>
            </li>
        </ul>
        <form name="itemForm" ng-submit="itemCtrl.addItem(list)">
            <input type="text" ng-model="itemCtrl.item.name">
            <input type="submit" value="Add Item">
        </form>
    </div>
</body>

Below is the Javascript code:

(function(){
var app = angular.module('notepadApp', []);

var shoppingLists = [
    {
        name: 'groceries',
        items: [
            {
                name: 'milk',
                checked: false
            },
            {
                name: 'eggs',
                checked: false
            }
        ]
    },
    {
        name: 'cvs',
        items: [
            {
                name: 'pills',
                checked: false
            },
            {
                name: 'cotton balls',
                checked: false
            },
            {
                name: 'cigs',
                checked: false
            }
        ]
    }
];

app.controller('notepadController', function(){
    this.lists = shoppingLists;
});

app.controller('ItemController', function(){
    this.item = {};

    // add new item to a shopping list
    this.addItem = function(list){
        list.items.push(this.item);
        this.item = {};
    };

    // remove an item from a shopping list
    this.removeItem = function(list){
        var listOfItems = [];

        var i;

        for (i = 0; i < list.items.length; i++){
            list.items.splice(list.items[i,1]);
        }
    };
});
})();

Please note that clicking on the Remove Item button currently clears all items from a list instead of targeting and deleting only the specific item intended. While I understand the cause of this issue, I am struggling to identify how to pinpoint the index of the item to be removed so that the Remove Item button functions correctly.

Answer №1

Consider this scenario for a moment. You are working with two controllers - one housing the list and the other managing the logic for individual items.

It's essential that any functions which modify the list reside in the same controller as the list itself.

Currently, you're faced with passing the entire list due to how the controllers are structured. It's becoming apparent where the issue lies with this setup.

Let's focus on the repeater:

ng-repeat="item in list"

This gives you access to each item, which is what should be passed into your function.

Similar to how you access the name of an item for display purposes, you can pass it into your removeItem function.

<form name="removeItemForm" ng-submit="notepad.removeItem(item)">
  <input type="submit" value="Remove Item">
</form>

The removeItem function should be located in the same controller as your list (hence why I changed itemCtrl.removeItem to notepad.removeItem).

In the notepadController:

this.removeItem = function(item){
  var index = this.list.indexOf(item);
  if (index > -1) {
    this.list.splice(index, 1); // remove the item
  }
};

Additionally, with ng-repeat, you can utilize a variable called $index to specify the index you wish to remove from the list:

ng-submit="notpad.removeItem($index)

Subsequently, the method would resemble this:

this.removeItem = function(index) {
  this.list.splice(index, 1);
}

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 incorporating an alt attribute into image tags using jquery

I recently inserted a Google map into a webpage and noticed that it generated multiple img tags without the alt attribute. I'm looking for a way to dynamically add the alt attribute to each img tag within a div using jQuery. Can someone suggest an alt ...

Unable to display service cost after passing ID through Ajax request for cost retrieval. The ID is successfully being passed, but the cost remains elusive

I've encountered an issue while trying to execute a seemingly simple ajax request. The goal is to send an "id" through ajax to fetch the service cost of an item with that specific "id". Although the ajax successfully sends the id to my "getcost.php" ...

Iterating through an array within an array in a React component

I am currently working on a basic React app where I have nested arrays and need to iterate over all the content. Here is my code snippet so far: {recipes.map((recipe) => ( <Recipe key={recipe.uid} title={r ...

Transferring a PHP session variable to JavaScript in a separate file

I successfully imported data from a CSV file into PHP and organized it into a nested array. To ensure the data is easily accessible across different files, I stored the array as a session variable. Now, the challenge lies in accessing this session variable ...

Recursive instruction malfunctioning

I'm currently trying to develop a custom recursion directive, but unfortunately it's not functioning as expected. I have followed the instructions outlined here: Recursion in Angular directives For reference, you can view the fiddle here: http ...

How to efficiently update a nested array within the state of a React

Although the onChange function is working as expected, I am facing issues with updating the features in the state. Despite numerous attempts, I haven't been able to find examples similar to what I'm trying to achieve, so I decided to seek help. ...

What is the best way to conceal a set of buttons on the main page using vue.js?

I'm having trouble hiding a button-group on the main page. It should disappear when either the button moveTo(0) is clicked or when scrolling to the top of the page. show: function() { this.scrollTop = (window.pageYOffset !== undefined) ? windo ...

No compatible version of Angular could be located

I'm receiving this error continuously. Any thoughts on why? $ bower install ng-roundabout --save bower cached git://github.com/angular/bower-angular-mocks.git#1.3.15 bower validate 1.3.15 against git://github.com/angular/bower-angular-moc ...

Sorry, but we couldn't locate the page you were looking for. The robots.txt file seems

Hey there everyone, I'm currently working with Nuxt3 and encountering an error when trying to access the robot.txt file. Here's the Robot.txt module that I've integrated. Within my nuxt.config.ts file: export default defineNuxtConfig({ ...

Looking to customize session data for my online game within the same interface

I have successfully coded a game called Ninja Gold using PHP with CodeIgniter. The game works by setting session variables (Gold and Activities) when the index page loads if they are not set already. Each location clicked adds a certain amount of gold to t ...

What is the method for avoiding short-circuit conditions in TypeScript?

Is there a way to evaluate conditions in TypeScript without using short-circuiting? TypeScript does not support & or | for boolean types. I need to avoid short-circuit checking because I call the showErrors function inside the isValueValid function. C ...

Transferring information from parent page to child page using Angular version 8.2.4

As a newcomer to Angular, I am facing a challenge in sharing data between pages upon loading the main page. The structure involves using dynamic forms to generate dynamic pages within the main page. However, when trying to pass data from the main page to t ...

Effective state management for numerous instances in Vue 3 using Pinia and Element Plus

I've encountered an issue where default objects sharing the same state are causing binding problems, making it difficult to separate them. Each instance needs its own independent state management. Both parent and child components exchange data and int ...

Securing access to third-party APIs by storing login credentials

Currently, I am in the process of developing a trading platform with Node & Express as the backend. Users of the platform will have their own login credentials for the application itself. However, in order for the platform to be fully functional, it al ...

Why does JavaScript not wait for the completion of forEach and instead executes the next line immediately?

While creating my api in nodejs and attempting to push the mongoose return count to a newly created array, it does not wait for the forEach loop to finish before executing json.res() and returning a null response. However, when I use setTimeout(), the re ...

Refreshing the page causes Material UI Button to revert to default styling

My question regarding the Material UI Button losing styling after a page refresh (link: Material UI Button loses Styling after page refresh) went unanswered, so I am reposting with a CodeSandbox included for reference: https://codesandbox.io/s/bold-resonan ...

Utilize a PowerShell array within a for loop

Although this may seem like a simple question about PowerShell, I am facing some difficulty with it. My goal is to move the contents of several folders from a staging area on a remote server to our DEV server. To make the code simpler, I stored the stagin ...

Stranger things happening when incorporating a generator function in React

Here's a simplified version of my component. It includes a generator function that cycles through values. const App = () => { const [state, setState] = useState("1") function* stateSwitch () { while (true){ yield "2" yield "3" ...

Wait for the playwright to detect a specific and exact change in the inner text

There is a specific innerText that transitions from Loading to Play after 2-3 seconds. I want to wait for this change to happen before proceeding. Currently, I am using the following code snippet: let attempt = 0; let maxRetries = 4; let payerButtonStatus ...

AngularJS Firebase Login Scope Value Not Retained After Refresh

I have stored my unique username in the variable "$scope" and I am trying to access it from different views once the user logs in, using: However, when I refresh the page immediately after the user successfully signs in, the value of "$scope" goes bac ...