Deleting lines from JSON object using Angular or JavaScript

On my webpage, I have a list where you can add a new line by pressing the "+" button (easy with push), but I'm not sure how to remove lines using the "X" button.

https://i.stack.imgur.com/nm06A.png

This is the JSON structure:

 "priceExtra" : [
    {
        "price" : NumberInt(2330), 
        "calc" : "1 x 2330", 
        "name" : "Foo price"
    }, 
    {
        "price" : NumberInt(5000), 
        "calc" : "2 x 2500", 
        "name" : "Baa price"
    } 
    {
        "price" : NumberInt(300), 
        "calc" : "1 x ฿300", 
        "name" : "Check-out full Cleaning"
    }
]

Here's my code for adding and removing lines:

//
// Add extra line
//
vm.addLine = () => {    
    vm.priceExtra.push(
        {
            name  : "", 
            calc  : "", 
            price : 0
        }
    ) 
}

//
// Remove line
//
vm.delLine = () => {    

}

The issue is that unique keys are lacking in the priceExtra array, even the "price" field could be duplicated on multiple lines.

Any suggestions on how to approach this problem?

I almost forgot to include the HTML:

<tr style="height:38px;" ng-repeat="extraLine in vm.priceExtra">
    <td class="book-mid" style="width:50%;" colspan="2">
        <input type="text" ng-model="extraLine.name" id="lineName" class="book-field book-field-slim ng-pristine ng-valid ng-not-empty ng-touched" aria-invalid="false" data-ng-change="vm.changeRent()">
    </td>
    <td class="book-mid-right" style="width:30%;">
        <input type="text" ng-model="extraLine.calc" id="lineCalc" class="book-field book-right book-field-slim ng-pristine ng-valid ng-not-empty ng-touched" aria-invalid="false" data-ng-change="vm.changeRent()">
    </td>
    <td class="book-mid-right" style="width:15%;">
        <input type="text" ng-model="extraLine.price" id="lineprice" class="book-field book-right ng-pristine ng-valid ng-not-empty ng-touched" aria-invalid="false" data-ng-change="vm.changeTotal()">
    </td>
    <td style="width:5%; text-align:right; padding-left:4px;">
        <button class="book-button book-text-button col-std-gray" ng-click="vm.newTenant=false">
            <md-icon class="material-icons book-material" aria-label="Close">close</md-icon>
        </button>
    </td>
</tr>

Answer №1

To remove an item from an ng-repeat list, simply access the index using $index:

...
<td style="width:5%; text-align:right; padding-left:4px;">
    <button class="delete-button delete-text-button col-std-gray" ng-click="vm.newItem=false; vm.removeItem($index);">
        <md-icon class="material-icons delete-material" aria-label="Close">close</md-icon>
    </button>
</td>
...

Then implement this function:

vm.removeItem = (index) => {    
    vm.listItems.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

What is the best way to ensure an AJAX get-request waits for the page to finish rendering before providing a response?

I've been working on a Greasemonkey Script for a specific section of this website (Site1). Site1 offers various deals and discounts, and my script is designed to perform the following task: When a user visits an offer on Site1, the script checks with ...

Navigation bar remaining fixed on mobile devices

I have been working on a bootstrap site at http://soygarota.com/blog/public After checking the code multiple times, I have added the bootstrap.min.css, bootstrap.min.js, and jQuery. However, for some reason, the header navigation is not collapsing when vi ...

What is the reason behind custom directives in AngularJS defaulting to being attribute-only?

Egghead.io offers a comprehensive explanation of directive restrictions within AngularJS. You can define a custom directive like this: angular.module("app", []).directive("blah", function () { return { restrict: "A", template: "blah di ...

Preventing file visibility in Three.js resource directory

Once a user clicks on a specific 3D model, I retrieve it from the server and render it in the browser using three.js. However, there is an issue when the user tries to access a model that is not free - they can easily view and download the STL file by go ...

What are the ideal scenarios for implementing React.Fragments?

Today I discovered React Fragments and their benefits. I learned that fragments are more efficient by reducing the number of tree nodes and improving cleanliness in the inspector. However, is there still a need to use div tags as containers in React compo ...

When I attempt to utilize the API, the JavaScript implementation of a <script src=...> element seems to interfere

Within one of my HTML files, I encountered the following line near the top: <script src="//maps.google.com/maps/api/js?key=apikey"></script> The API key is currently hardcoded in this file, but I would like to use a configuration option store ...

Assistance required for implementing JSON post functionality on EpiServer CMS versions above 8.0.0

We are currently implementing JSON posting to a site monitoring API across multiple EpiServer sites. The process works smoothly on our EpiServer CMS version 8.0.0 sites, but we encountered issues with versions 8.8.1 and above. Here is our successful worki ...

Tips for showcasing axios data on Vue components

I'm just starting out with Vue.js and I'm struggling to grasp how it all works. I have a function that sends data to the server and receives a response using axios. However, when I try to display the response using a variable, something seems to ...

Utilizing HTML5 history instead of hash URLs to preserve the user's browsing history

Our application is a single page that dynamically loads results based on query strings. The query string format we use is as follows: ?city=Delhi&pn=1 Within the SPA, there are different sections displayed on the same page. As users navigate through ...

Issues with sending emails through Nodemailer in a Next.js project using Typescript

I'm currently working on a personal project using Nodemailer along with Next.js and Typescript. This is my first time incorporating Nodemailer into my project, and I've encountered some issues while trying to make it work. I've been followin ...

Difficulty encountered while using React.js map function to access specific JSON data

I'm encountering an issue where I am unable to read data from a JSON file. After checking that the data is stored in the component state and logging it to the console once the component is mounted, I attempted to render the URL string from the JSON da ...

Retrieve data from cookies that have been stored by the node server on the front end

I am currently utilizing the Node package 'cookie' to establish cookies from the backend as shown below: res.setHeader('Set-Cookie', cookie.serialize('token', token, { maxAge: 60 * 60 * 24 * 7 // 1 week ...

Issue with typings in TypeScript is not being resolved

I have integrated this library into my code Library Link I have added typings for it in my project as follows Typings Link I have included it in my .ts file like this import accounting from "accounting"; I can locate the typings under /node_modules ...

The gulp plugin useref mistakenly concatenates JavaScript files multiple times

I am struggling with a gulp task that I need help with gulp.task('html', [], function() { var partialsInjectFile = gulp.src(options.tmp + '/partials/templateCacheHtml.js', {read: false}); var partialsInjectOptions = { ...

Preventing Canvas Image Disappearance with JavaScript's onload Event

My current issue involves adding an Image to my webpage. However, every time I hit the refresh button, the image disappears. After researching on Stack Overflow, it was suggested to include window.onload=yourDrawFunction() in the code. Despite following th ...

Updating nested array values with variables

I'm facing a JQ issue with JSON data that I'm unable to solve. Here is the JSON structure: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", &q ...

Is it considered acceptable to retrieve the action payload in mapDispatchToProps in a React/Redux setup?

In my MediaUpload component, I have a mapDispatchToProps function that handles file uploads. When a file is added, the onChange handler triggers two actions: creating new media entries for the files and updating the form data in the state with the generate ...

Obtaining Local JSON data in a standard Flutter class

In the Services-> math_logic.dart file, I have a page dedicated to mathematical calculations where I did not use StateFul Widget. However, I encountered an error indicating that 'Future is not a subtype of String'. It seems that there was also ...

how to set up automatic login for a user after changing their password using passport-local-mongoose

Trying to automatically log in a user, but encountering an issue with the current 'update' function that looks like this exports.update = async (req, res) => { const user = await User.findOne({ resetPasswordToken: req.params.token, re ...

An effective method for linking a value from one ng-model to another is by identifying and matching a specific string

I have been tasked with binding a value to one model based on the content of another model when it contains a string that starts with "https". For instance, there are two text fields each associated with a different model. <input type="text" ng-model= ...