Deleting object property within Angular ng-repeat loop

I have information structured like this:

$scope.cart={"4": {"cost": 802.85,  "description": "test", "qty": 1},
"5": {"cost": 802.85,  "description": "test", "qty": 1}};

My goal is to iterate through this data and show it with a remove button. How can I set up the button to delete the row from the scope and trigger an angular digest? Most tutorials deal with data in arrays and splicing them, which isn't suitable for my situation.

This is my progress so far: http://jsfiddle.net/wbebc4cd/1/

Answer №1

As per @dfsq's observation, it appears there is a typo in your function.

Additionally, when iterating over the map, it is crucial to remember the key as well. For further information, refer to How to use ng-repeat to iterate over map entries in AngularJS

<tr ng:repeat="(key,item) in cart">

This way, you can utilize the key to eliminate the specific item.

<td>[<a href ng:click="removeItem(key)">X</a>]</td>

Access the following link for more details and illustration: http://jsfiddle.net/wbebc4cd/5/

Answer №2

Follow this code snippet for removing the desired item from the list.

function CartForm($scope) {
    $scope.cart=[{"id": 1, "cost": 802.85,  "description": "test", "qty": 1}, {"id": 2, "cost": 802.85,  "description": "test", "qty": 1}];


    $scope.removeItem = function(item) {
        var index = $scope.cart.indexOf(item);
        $scope.cart.splice(index, 1);

    }


}

Answer №3

Here is a potential solution for removing an item from the cart:

$scope.removeItem = function(item) { 
    var newCart = {};
    angular.forEach($scope.cart, function(value, key){
        if(value != item)
            newCart[key] = value; 
    });

    $scope.cart = newCart;   
};

To see this code in action, you can check out the JSFiddle link provided: http://jsfiddle.net/0v40rhfb/2/

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

CSS- Strategically placing and centering images above specific keywords in (any) HTML content without disrupting the flow of text

My main objective involves dynamically inserting images above text on any given page using a content script. The challenge lies in maintaining the proper alignment of the text after adding the images. To achieve this, I surround the words where the image i ...

What could be causing json_decode to return NULL in this scenario?

I have a custom array that I've created with the following structure: [{ "assetPreviewUrl":"pic1.jpg", "assetUrl":"pic2.jpg" }, { "assetPreviewUrl":"pic3.jpg", "assetUrl":"pic4.jpg" }] My approach involves stringifying this array and ...

The lack of definition for the props value poses an issue in React.js Hooks

I'm currently developing a notepad web application that utilizes React Hooks for managing state variables. In order to fetch data from an API, I am using the axios library. The retrieved data consists of objects with fields such as _id, title, status, ...

javascript strange behavior observed with multidimensional array

Looking to create a jquery autocomplete input that responds to the user's input from a previous field. I have a php script that returns a json variable, but I'm having trouble setting up my array correctly afterwards. I've attempted settin ...

Unable to save or create files in Store.js

Recently, I've been trying to save a file on client storage using Store.js. After changing the date with store.set and logging it to the console successfully, I encountered an issue where the data was not being saved in the app directory as expected. ...

When using ng-repeat in Angular.js, an additional td is created

https://jsfiddle.net/gdrkftwm/ https://i.sstatic.net/CTi2F.jpg I have encountered a problem while creating a table from a Json object. There seems to be an extra td being generated, and I'm not sure why. I want the structure of my table to resemble ...

Utilizing a dropdown selection to trigger an IF statement in a function

I have an HTML code snippet as shown below: The value "Test" is just for my reference to ensure that the code is functioning properly :) <script> var tfa78 = document.getElementById("tfa_78").selvalue; if( tfa78 == "karte" ) { document.getEl ...

Vuex getters not displaying expected values in computed properties until entire page has finished loading

When working with computed properties using data fetched by the mapGetters function in my Vuex store, I always encounter the issue of getting an undefined value until the entire page or DOM is fully loaded. For instance, I have an example of an isRegister ...

What is the appropriate overload to be selected when utilizing a ref in the method call?

Encountering an unfamiliar TS error while working with the code snippet below: <script lang="ts"> import {defineComponent, computed, toRef} from 'vue' import _ from 'lodash' import {DateTime} from 'luxon' int ...

Develop an array in JavaScript using PHP on the server side

I have successfully created a JavaScript array in PHP and sent it to the client. However, I am now wondering how to create a JavaScript array with PHP and store it on the server. Can anyone provide some guidance on this? Thanks in advance! ...

What steps can I take to reset my JavaScript code once its original purpose has been fulfilled?

I created this code, learning as I went along. It measures Beats Per Minute as one clicks the left-mouse-button each time they feel a pulse. After 10 clicks, the JavaScript code takes all the values in the array and calculates an average BPM. The issue ar ...

I am facing difficulty in retrieving a unique dynamic div id using the useRef ReactJS hook, as it keeps returning the same id repeatedly

When using the useRef Reactjs hook, I encountered an issue where it returned the same id repeatedly instead of generating a dynamic div id. I need this functionality to map buttons and div ids in order to create a flexible accordion. The goal is to displ ...

Is there a way for me to determine which class has been selected using jQuery and JavaScript?

I created a list containing various links: <li class="link-1"><a href="#">One</a></li> <li class="link-2"><a href="#">Two</a></li> <li class="link-3"><a href="#">Three</a></li> .. Wh ...

Oops! Looks like something went wrong. The command to install the debug app failed because the emulator could not be launched. This could be due to the fact that no emulators were found

I'm in need of assistance to resolve these issues Encountered an error while trying to install the app. Please ensure that your Android development environment is properly configured: https://reactnative.dev/docs/environment-setup. Error: Command fai ...

What's the best way to fill checkboxes in EJS when editing a route?

As a beginner, I am working on my first project - a simple content/property listings app. I have created a form to collect user data and display it on a show form. The form includes sections for checkboxes and radio buttons, with the values being stored i ...

Issue with scroll being caused by the formatting of the jQuery Knob plugin

I am currently utilizing the jQuery Knob plugin and I am looking to have the displayed value shown in pound sterling format. My goal is for it to appear as £123456. However, when I attempt to add the £ sign using the 'format' hook, it causes is ...

"Unexpected behavior: Angular route parameters are found to be empty upon receiving the API

Seeking to extract parameters from the urlcallback received from an external authentication source, within my Angular project using angular-route/$routeProvider The API redirect is as follows: http://localhost:8080/dist/?somevar=someval&val2=someot ...

Text that changes within a set-sized box

I'm working with a fixed-size div that contains dynamically generated text. Is there an easy method using DOJO or plain Javascript to truncate the text before the end of the div and add "..."? How can I accomplish this regardless of the font size bein ...

Master the art of navigating the Windows Sound Recorder with the power of JavaScript

I am creating a project that involves controlling the Windows sound recorder for tasks such as starting, stopping, and saving recordings. Is there a way to do this without displaying the recorder window? I would appreciate any assistance in solving this. ...

Ensure Safari sends the Origin header in jQuery GET requests

When I send a request from https://app.example.com, the following code is executed: $.get('https://api.example.com', { foo: 'bar' }) .success(getSuccess) .error(getError); This script runs smoothly on Chrome and Firefox, however, ...