Manipulating a dynamic array within an Angular repeater using the splice method

Encountering an issue with deleting an object from an array using splice. The array, dynamically created through a UI, is stored in $scope.productAttributes.Products. Here's an example of the array structure...

[
{
    "ProductLabel":"Net",
    "Code":"ela",
    "Site":"SITE1"
},
{
    "ProductLabel":"Link",
    "Code":"eli",
    "Site":"SITE1"
},
{
    "ProductLabel":"24-port managed PoE switch",
    "Code":"24p",
    "Site":"SITE2"
},
{
    "ProductLabel":"Dedicated Firewall",
    "Code":"ded",
    "Site":"SITE2"
},
{
    "ProductLabel":"Link",
    "Code":"eli",
    "Site":"SITE3"
},
{
    "ProductLabel":"IPv4 Addresses",
    "Code":"ip4",
    "Site":"SITE3"
}
]

The array is displayed using an angular repeater grouping it by 'site'...

<div ng-repeat="(key, value) in productAttributes.Products | groupBy: 'Site'">
    <strong>{{key}}</strong>
    <div ng-repeat="site in value">
        <h4>{{site.ProductLabel}}</h4>
        <span href="" ng-click="deleteItem($index)" class="text-danger">Remove {{site.ProductLabel}}</span>
    </div>
</div>
</div>

A delete button triggers the splice function using the passed index...

 $scope.deleteItem = function (index) {
        $scope.productAttributes.Products.splice(index, 1);
};

The issue arises with $index always being zero due to nested repeater's structure. Any suggestions on how to rectify this?

UPDATE:

Issue seems related to $index in the nested repeater as shown below...

SITE1:

Product: Net - $index: 0

Product: Link - $index: 1

SITE2:

Product: 24-port - $index: 0

Product: Dedicated - $index: 1

SITE3:

Product: Link - $index: 0

Product: IPV4 - $index: 1

Deleting IPV4 mistakenly removes LINK in SITE1 due to same $index. Suggestions for a solution?

Answer №1

Never depend solely on $index for retrieving values as it may not reflect the correct value after removing an element from the array.

To ensure accurate deletion, pass the object dynamically from the UI and implement the following code to remove it from the model:

In Your HTML Template:

<div ng-repeat="(key, value) in productAttributes.Products | groupBy: 'Site'">
    <strong>{{key}}</strong>
    <div ng-repeat="site in value">
        <h4>{{site.ProductLabel}}</h4>
        <sapn href="" ng-click="deleteItem(site)" class="text-danger">Remove {{site.ProductLabel}}</span>
    </div>
</div>

Implementation in JavaScript:

$scope.productAttributes.Products.splice
    ($scope.productAttributes.Products.indexOf(site), 1);

This method ensures that the model is updated with the latest changes and reflects them accurately in the user interface.

Answer №2

After trying a new approach, I managed to solve the issue successfully.

$scope.removeItem = function (selectedItem) {
        var idx = $scope.itemList.Items.indexOf(selectedItem);
        $scope.itemList.Items.splice(idx, 1);
    };

Surprisingly, passing in the entire object proved to be effective this time. The reason behind its success remains unknown to me.

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

Following the ajax request, the subsequent code was unable to be executed as it awaited the JSON response

My latest project involves using Django2 to create a web application. I encountered an issue in the frontend where, despite receiving a 200 status code in the network tab after an ajax call, no alert box was displayed. The app seemed to be stuck at a parti ...

Personalized Dropdown Menus for Internet Explorer 8

Seeking recommendations for stylish custom select boxes that are compatible with IE8 and function flawlessly. Many of the custom scripts I've come across perform admirably, but tend to suffer setbacks when it comes to working smoothly in IE8. ...

Stacked column tooltip displaying an array of 3 values

I am working with a json code that looks like this: [[1385420403000,9.86,6.91],[1385506802000,11.89,6.57],[1385593203000,14.11,10.58],[1385679602000,9.1,8.9],[1385766003000,13.59,7.53],[1385852402000,10.68,6.69],[1385938803000,11.03,10.52],[1386025202000, ...

Retrieving HTML elements from the website address

Imagine having a URL like www.example.com. On this webpage, there is a DOM element <a>. To programmatically click on this element, you would typically use document.getElementById('#link')[0].click(). The challenge arises when dealing with ...

Uncovering Inline Styles Infused with Javascript for Effective Debugging of Javascript Code

SITUATION: I have recently inherited a website from the previous developer who has scattered important functions across numerous lengthy JS files. I am struggling to track down the source of an inline CSS style within the JS or identify which function is d ...

Updating the value of a Redux-Form Checkbox Field using programming methods

I have created a registration form where users can accept or decline the terms of services. When a user accepts the terms, they click a button to check the checkbox. If they decline, the button will uncheck the checkbox. https://i.sstatic.net/mfkcY.png ht ...

Issue with Nodemailer OAuth2 2LO authentication when deployed on Heroku

const { EMAIL_FROM, EMAILS_TO, USER, GMAIL_CLIENT_ID, GMAIL_PRIVATE_KEY } = process.env; let transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 465, secure: true, auth: { type: &a ...

Rendering DataTable content seamlessly from a different webpage using JavaScript without sacrificing control

Is it possible to dynamically call HTML content from Page2.html into Page1.html by utilizing DataTables (https://datatables.net/)? Page1.html <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" c ...

What is the best way to implement complex input filtering in JavaScript?

Is it possible to filter input content in this format? The input should accept 16 characters, separated into 4 groups by ":" like this: 0123:0055:02AC:01FA I divided them into 4 groups for later use, but I want to set a filter with the minimum value bei ...

alter objective response

Currently, I am in the process of developing an educational game for children inspired by the classic "whack-a-mole" style. In this game, kids are presented with a math question and must click on the correct number that appears to solve it. For instance, i ...

What is the best locator to use for this specific input field in the code?

Can someone help me figure out how to locate and fill in another input field in the code snippet below? '<input _ngcontent-tvt-19="" class="form-control ng-pristine ng-valid ng-touched" placeholder="You can search keywords" type="text"> I&apos ...

Releasing Typescript 2.3 Modules on NPM for Integration with Angular 4

Although there are instructions available in Writing NPM modules in Typescript, they are outdated and there are numerous conflicting answers that may not be suitable for Angular. Additionally, Jason Aden has delivered an informative presentation on youtu ...

There is an error in ReactJS: TypeError - _this.props.match is not defined

I am experiencing a TypeError in my console tab and I can't seem to figure out where the error is occurring in my source code. I am relatively new to ReactJS so any help in identifying what I'm doing wrong would be greatly appreciated. Thank you ...

The error message indicates that the argument cannot be assigned to the parameter type 'AxiosRequestConfig'

I am working on a React app using Typescript, where I fetch a list of items from MongoDB. I want to implement the functionality to delete items from this list. The list is displayed in the app and each item has a corresponding delete button. However, when ...

Is it common to encounter a "no such file or directory" error when running Docker-Compose with the command "ENTRYPOINT ['./init.sh']" in a Dockerfile?

Contemplate the docker-compose configuration : version: '3.0' volumes: data: driver: local networks: simple-network: driver: bridge services: postgres: container_name: postgres image: postgres ...

Receive an odd array element

When I load a single data from the database, it appears as an array. However, I am unsure how to extract the value in label_values. Print_r($results): Array ( [custom_params] => custom_limit="0"|input_label="{\"label_values\":[\"\u ...

Nextjs: Issues with Dropdown functionality when using group and group-focus with TailwindCSS

My goal is to make an array visible once a button is clicked. By default, the array should be invisible, similar to drop-down menus in menu bars. I am utilizing the group and group-focus classes. While the array disappears as expected, it does not reappear ...

What is the process for calling app.vue methods from an ES6 module?

I am currently in the process of constructing a vuejs application using webpack, vuex, and vue-router. The organization of my project is as follows: [components] BlockingLayer.vue [store] index.js [restapi] index.js App.vue main.js Within App. ...

Invalid web address entered

While attempting to incorporate a functionality that opens a new window to a specific link when clicking an icon, I encountered an issue where the click action redirects to the wrong URL. Instead of directing to the URL specified in its href attribute, it ...

Customizing the appearance of jQuery accordion components

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js" language="javascript"></script> <script type="text/javascript" src="http://www.compactcourse.com/js/accordionNew.js" language="javascript"></script> < ...