What could be causing the ng-repeat to remove the incorrect item when splicing?

I'm encountering an issue while trying to splice out items in this ng-repeat based on their $index. Although it works perfectly for adding items, when attempting to delete an item using the same code, it ends up removing only the last item of the array as if employing the pop() method. I am baffled by this behavior. Here's the object that I'm repeating:

"lineItems": [
  {
    "area": "Bedroom",
    "label": "Sleep Time",
    "notes": "",
    "pictures": [],
    "subLineItems": [
      {
        "label": "Flooring",
        "data": {
          "rates": [
            {
              "label": "Damaged",
              "value": "1",
              "color": "damaged-red"
            },
            {
              "label": "Poor",
              "value": "2",
              "color": "poor-orange"
            },
            {
              "label": "Dirty",
              "value": "3",
              "color": "dirty-yellow"
            },
            {
              "label": "Fair",
              "value": "4",
              "color": "fair-light-blue"
            },
            {
              "label": "Good",
              "value": "5",
              "color": "good-green"
            }
          ]
        },
        "items": [
          [
            {
              "uuid": "6f5fed0c-db03-41a0-a575-15af3ad3",
              "label": "Hot Water Tank",
              "selected": false,
              "price": 500,
              "labor": [
                {
                  "uuid": "8b9f9ea2-b163-45c0-9a80-087a8e16",
                  "label": "Install Carpet Basic",
                  "selected": false,
                  "price": "1.00"
                },
                {
                  "uuid": "a696faca-197a-4fd9-972c-05f197f4",
                  "label": "Install Trim Basic",
                  "selected": false,
                  "price": "0.50"
                },
                {
                  "uuid": null,
                  "label": "Select",
                  "selected": true
                }
              ]
            },
            {
              "uuid": "7815a160-7b70-48d1-ba32-8c232654",
              "label": "Ceiling Fan Replacement",
              "selected": false,
              "price": 175,
              "labor": [
                {
                  "uuid": "8b9f9ea2-b163-45c0-9a80-087a8e16",
                  "label": "Install Carpet Basic",
                  "selected": false,
                  "price": "1.00"
                },
                {
                  "uuid": "a696faca-197a-4fd9-972c-05f197f4",
                  "label": "Install Trim Basic",
                  "selected": false,
                  "price": "0.50"
                },
                {
                  "uuid": null,
                  "label": "Select",
                  "selected": true
                }
              ]
            },
            {
              "uuid": null,
              "label": "Select",
              "selected": true
            }
          ]
        ],
        "rate": null,
        "notes": null,
        "pictures": []
      }

Here is my HTML:

                            <ul class="list-inline col-xs-12">
                                   <form class="form-inline col-xs-12" id="expenseForm">
                                   <!-- li = items[0].array -->
                                      <li ng-repeat="item in subLineItem.items track by $index" class="bouncy-slide-left" ng-class-even="'even-stripe'">
                                         <!-- MATERIALS -->
                                         <div class="form-group col-xs-3" style="margin-left: 0px !important">
                                            <label for="material">{{labels.material.label}}</label>
                                            <br>
                                            <select name="material" class="form-control" ng-model="expense.mat.item" style="width: 125px">
                                               <option value="{{mat.uuid}}" ng-repeat="mat in item" ng-selected="mat.selected">{{mat.label}}</option>
                                            </select>
                                         </div>
                                         <div class="form-group col-xs-2">
                                            <label>{{labels.material_qty.label}}</label>
                                            <br>
                                            <input type="text"  ng-model="item.mat.qty" class="form-control" name="quantity" placeholder="{{labels.material_qty.placeholder}}" style="width: 55px; overflow: scroll">
                                         </div>
                                            <div class="form-group col-xs-2">
                                            <label>{{labels.material_cost.label}}</label>
                                            <br>
                                            <input type="text" ng-model="expense.mat.price" class="form-control" name="labor"  placeholder="{{labels.labor_cost.placeholder}}" style="width: 55px; overflow: scroll">
                                         </div>
                                         <div class="form-group col-xs-2">
                                            <label>{{labels.totals.total}}</label>
                                            <br>
                                            <input type="text" ng-model="expense.mat.total" class="form-control" name="labor" placeholder="{{labels.labor_cost.placeholder}}" style="width: 55px; overflow: scroll">
                                         </div>
                                         <div class="icon-str col-xs-1" style="padding-left: 0px" ng-click="removeItem($parent.$parent.$index, $parent.$index, $index)">
                                                <label for=""></label>
                                                <br>
                                                <i class="fa-trash delete-inspec"></i>
                                            </div> 
                                        <!-- LABOR  ITEMS -->
                                         <div class="form-group col-xs-3">
                                            <label for="labor">{{labels.labor.label}}</label>
                                            <br>
                                            <select name="labor" class="form-control" ng-model="item.lab.item" style="width: 125px">
                                               <option value="{{lab.uuid}}" ng-repeat="lab in item[0].labor" ng-selected="lab.selected">{{lab.label}}</option>
                                            </select>
                                         </div>
                                         <div class="form-group col-xs-2">
                                            <label>{{labels.material_qty.label}}</label>
                                            <br>
                                            <input type="text" ng-model="item.lab.qty" class="form-control" name="hours" placeholder="{{labels.labor_qty.placeholder}}" style="width: 55px;overflow: scroll">
                                         </div>
                                         <div class="form-group col-xs-2">
                                            <label>{{labels.labor_cost.label}}</label>
                                            <br>
                                            <input type="text" ng-model="item.lab.price" class="form-control" name="labor" placeholder="{{labels.labor_cost.placeholder}}" style="width: 55px;overflow: scroll">
                                         </div>
                                         <div class="form-group col-xs-2 ">
                                            <label>{{labels.totals.total}}</label>
                                            <br>
                                            <input type="text" ng-model="item.lab.total" class="form-control" name="labor" placeholder="{{labels.labor_cost.placeholder}}" style="width: 55px;overflow: scroll">
                                         </div>
                                         <!-- RESPONSIBLE PARTY -->
                                         <div class="form-group row col-xs-12" style="margin-left:0px !important; padding-left: 0px; padding-bottom: 10px; border-bottom: 2px solid #888">
                                           <div class="col-xs-5 text-left" style="padding-right: 0px">
                                                <label for="expenses">{{labels.responsible.label}}</label>
                                                <br>
                                                <select name="expenses" ng-model="expense.responsible" class="form-control" style="width: 200px">
                                                   <option value="{{resp.value}}" ng-repeat="resp in labels.responsibleParty" ng-selected="resp.selected">{{resp.label}}</option>
                                                </select>
                                            </div>
                                         </div>
                                      </li>
                                   </form>
                                </ul>

Here is my controller :

   //add line item when NEW button is pressed
   $scope.add = function(a, b){
       //create the source of the copy, and where you want to send it (destination is a blank array)
       var mySource = $scope.lineItems[0].subLineItems[0].items[0];
       var myDestination = [];
       //copy the source and send it to destination
       angular.extend( myDestination, mySource);
       //push that newly built array into the array
       $scope.lineItems[a].subLineItems[b].items.push(myDestination);
       //show the updated version of that array
       console.log( $scope.lineItems[a].subLineItems[b].items);
   };
   //remove item from array
   $scope.removeItem = function(a, b, c){
       console.log(a, b, c);
       $scope.lineItems[a].subLineItems[b].items.splice(c, 1);
       console.warn($scope.lineItems[a].subLineItems[b].items);
   };

This prints the correct number in your console but actually removes the last item in the items array. Any Ideas?

Answer №1

Your issue lies within the parent elements.

removeItem($parent.$parent.$index, $parent.$index, $index)

In this context, the $parent refers to the structure of your HTML rather than the array itself. Consider exploring alternative strategies for targeting the nested arrays.

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

Execute the Angular filter again when there is a change in the scope

I am currently working on an application where Users have the ability to switch between kilometers and miles for unit distances. To handle this, I created a custom filter that converts the distances accordingly: app.filter('distance', function() ...

Getting the value of a variable within the scope of AngularJS can be achieved by utilizing

I have an ng-repeat directive in my code that displays slides. Here is a snippet of the data: slides = [{ src: "/sikiosk/slidedata/Global/NA/USNS/Cafeteria/5000_24.jpg", interval: 5000 }, { src: "/sikiosk/slidedata/Global/NA/USNS/Cafeteria/5000_login-regi ...

Implementing text truncation in JavaScript

I am seeking to transform the INPUT I have into a desired OUTPUT format. pieChart.js stackedColumnChart.js table.js and i want OUTPUT like that(wanna remove .js from ) pieChart stackedColumnChart table ...

Refresh the angular list filter by clicking on it

I'm struggling with updating an Angular list after the filter is changed. Below is the HTML code I am using: <li ng-repeat="items in list | filter:filterList" style="list-style-type:none"> {{items}} </li> Additionally, here is the o ...

Exploring AngularJS concepts with a focus on understanding view problems (ng-if, ng-switch)

As a beginner diving into the world of AngularJS and JavaScript, I find myself facing a challenge that I hope to get some advice on today. The issue revolves around displaying an input block with or without the "readonly" attribute. To better explain my pr ...

What method would you recommend for monitoring a json file effectively?

Important Information: Currently, I am in the process of generating a json file via Matlab that constantly updates with the most recent coordinates. To accomplish this task, I have opted to utilize JsonLab for writing the file from Matlab to json. Dilemm ...

How to test an AngularJS controller that utilizes a service which returns a promise

I am currently creating unit tests for my components. After conducting thorough research, I have come to the realization that testing components that rely on services can be quite cumbersome and may require some messy work. I am feeling unsure about the ...

Incompatible parameter type for the Angular keyvalue pipe: the argument does not match the assigned parameter type

I need to display the keys and values of a map in my HTML file by iterating over it. To achieve this, I utilized Angular's *ngfor with the keyvalue pipe. However, I encountered an error when using ngFor: The argument type Map<string, BarcodeInfo ...

When making a Get Request from Angular, the header fails to appear for servicing

I am currently working on an angular JS application where I need to call a GET API that is OAuth 2.0 enabled, requiring a Bearer Token in the header for authentication. The method I am using to make the HTTP request is as follows: var config = { heade ...

A guide on displaying information from an array of objects using MongoDB and AngularJS

I need assistance with appending data to a div using ng-repeat. Currently, I am working with angularjs and MongoDB but without mongoose. Any guidance on this would be greatly appreciated. Here is an array of objects retrieved from the server: [ { ...

Tips for merging conditional and data binding classes in AngularJS

In order to dynamically apply different classes based on expressions in your AngularJS templates, you can make use of the ng-class directive. Here is an example: <div ng-class="{'class1' : expression1, 'class2' : expression2}"> ...

What is the best way to automatically select a checkbox when using ng-repeat on page

I'm looking to automatically check an input checkbox when the page loads, and if it's checked, subtract its value from the total. How can I tackle this issue? Here's the HTML snippet: <p>{{vm.TOTAL VALUE}}</p> <tr ng-repeat= ...

What is the best way to set a default selected value in an input text box?

Incorporating the typeahead feature into my project has been incredibly useful: <input type="text" ng-model="customPopupSelected" placeholder="Custom popup template" uib-typeahead="state.id as state.desc for state in states | filter:{name:$viewValue ...

An in-depth guide on troubleshooting routeProvider problems in Angular JS with code samples

I recently started delving into angular js and following tutorials on egghead.io. One of the examples I am working with involves routeProvider. I am using vs.net 2012 to test it out, but I am having trouble getting the templates or messages to display when ...

"Error message 'querySelector' property or method is not supported on this object" is displayed when trying to access the website using the machine name in Internet Explorer 11

I am facing an issue with my AngularJS site deployed on IIS in a Windows Server 2012 R2 environment behind the firewall. When accessing the site through RDP on the server and typing in http://localhost/Foo in Internet Explorer 11, everything works fine ...

What is the best way to transfer JSON data to a different controller in AngularJS?

Hello, I'm still learning AngularJS and facing an issue with the following code snippet. app.config(function($routeProvider) { $routeProvider .when('/', { templateUrl: "partials/home.html", controller: "mainControlle ...

Make sure to wait for the current operation to finish before moving onto the next one

In the primeData function within the datacontext, four queries are made to a back-end Web API service: function primeData(forceRefresh) { return (getLookups(forceRefresh) // this needs to complete before moving on .then(success)) ...

Assign a specific value to be selected in an ng-option by using ng-repeat

<li class="list-group-item" ng-repeat="entity in displayedProjectRoles"> <div> <strong>Role: </strong> <select ng-model="project.role" ng-options="option as option.name for option in ...

How can I update the datasource read URL and refresh the Kendo UI Grid with parameters?

I am working on a single page application using KendoUI and AngularJs. Within this application, I have two grids that are managed by two separate controllers. My goal is to pass the movieId of the selected row in the first grid to the second controller in ...

How to retrieve an array value within a function in AngularJS

<select class="form-control" id="column" ng-model="selectedcolumn" ng-options="column for column in columns"></select> <input type="text" ng-model="test[selectedcolumn]" ng-change="search()" /> Is there a way to retrieve the value o ...