Trouble removing item from array in AngularJS

I've encountered an issue in Angular where I am trying to remove an element, but I keep receiving an Error: [ngRepeat:dupes] after deleting an item from the list.

This is how my controller is set up:

app.controller("ListController",[function () {
    this.tasks = [
      { id: 1, taskName : "Task 1", badge : 10 },
      { id: 2, taskName : "Task 2", badge : 12 },
      { id: 3, taskName : "Task 3", badge : 14 },
      { id: 4, taskName : "Task 4", badge : 15 }
    ];

    this.remove = function(id) {
        var key;
        for (key in this.tasks) {
          if(this.tasks[key].id === id) {
            var found = true;
            break;
          }
        }

        if(found) delete this.tasks[key];
    }
}]);

And here's how it is displayed in the view:

  <li class="list-group-item" ng-repeat="task in ListCtrl.tasks">
     <span class="badge">{{task.badge}}</span>
     <button type="button" class="btn btn-xs btn-danger" ng-click="ListCtrl.remove(task.id)"><i class="glyphicon glyphicon-remove"></i></button>
     {{task.taskName}}
  </li>

This error message keeps popping up:

 Error: [ngRepeat:dupes] http://errors.angularjs.org/1.3.13/ngRepeat/dupes?p0=task%20in%20ListCtrl.tasks&p1=undefined%3Aundefined&p2=undefined
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:6:417
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:233:39
at Object.fn (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:122:63)
at l.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:123:138)
at l.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:126:58)
at HTMLButtonElement.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:215:36)
at HTMLButtonElement.c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:32:389)

Answer №1

When using ng-repeat, an incremental counter is utilized to list out arrays. If you happen to remove a key from the middle of your array, Angular will recognize that specific element as undefined. While one undefined value may not be problematic, having two can result in duplicates (since ng-repeat does not allow for two elements with the same value) - leading to duplicate undefined values.

The recommended solution is to remove the object using Array.splice().

If you opt to use track by $index, it can resolve the duplication issue but might leave you with empty elements within your HTML.

Here is a link to an in-depth discussion on this matter in the Angular GitHub issue. The Angular team has decided to maintain the current state.

Here is a helpful guide on how to remove a specific element from an array using Array.splice().

Answer №2

To delete items from an array when dealing with an array of objects, you can utilize the Array.splice(index, count) method.

Answer №3

Implement the trackby index feature when using ng-repeat

ng-repeat="item in ListCtrl.items track by $index"

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

Vue3 - Implementing a seamless communication channel between two child components

Vue 3 has brought about changes in my component structure, as shown below: https://i.sstatic.net/bgtPB.png In this setup, ChildA can communicate with ChildB and requires ChildB to update its state accordingly. In Vue 2, I could send an event from ChildA: ...

Is it not possible to use array splice with a string that is in array format (i.e., split string

Why doesn't array splice work with a string that has been formatted into an array using the split() method? function _formatText(text) { var textList = text.replace(/\s+/g, ",").split(","); return textList.splice(1, 0, "<br />").join ...

A guide on generating indices for icosahedronbuffergeometry using three.js

I am facing an issue and struggling to find a solution. I am looking for an alternative method to texture a sphere in three.js by using icosahedronbuffergeometry instead of spherebuffergeometry with additional code to generate indices for rendering using d ...

Encountering a blank screen on the Swagger route in ExpressJs: How to troubleshoot

I have set up swagger-ui-express with swagger-jsdoc in my Express.js project following various tutorials and official documentation. However, despite implementing everything correctly, I am facing an issue where the Swagger URL displays a blank white scree ...

When creating a FlipCard, you may encounter the error message "The object may be null" while using the document.querySelector() method

Having trouble creating a flipcard on Next.js with tsx. The querySelector('.cardflipper') doesn't seem to locate the object and I keep getting this error: "Possibly the object is null". Does anyone know a solution to help my method recognize ...

Tips for creating an efficient, versatile, and error-proof function using Javascript

There is an Object that can take on three different forms: {done, key, value} {done, key} {done, value} When two of these Object instances are passed to a function, it needs to handle all three cases like a logical or operation. This is the approach tak ...

Error message: "Attempting to update /mytable using the `UPDATE` SQL command on React App localhost:MYPORT with react-postgres and PostgreSQL / node.js backend is not allowed."

Following the tutorial located at https://github.com/nsebhastian/react-node-postgres, I have successfully implemented the full guide, as evidenced by the results documented in TypeError: Cannot read property 'rows' of undefined. The functionalit ...

How to effectively test $transition service hooks in UI-Router 1.X using karma?

I have been working on migrating to ui-router 1.0.5 and have made good progress, but I am having trouble finding examples of how to test the new transition hooks that replaced the $stateChangeXXX event listeners. Previous Code: scope.$on('$stateChan ...

Tips for managing DOM elements with AngularJS filters while keeping them hidden rather than removing them

When using Angular's ng-repeat with a filter, I made an interesting discovery by inspecting the DOM in Chrome's developer tools: Instead of just hiding nodes that don't meet the filter condition, Angular actually removes them and then re-re ...

Is there a way to determine the dataType when an Array is converted into an ArrayBuffer?

I am dealing with an array: const dataArray = new Uint16Array(256); Later on, this array is transferred to another computer using nodeJs with the binaryType set to "arraybuffer". How can I determine on the receiving client whether to cast the array as U ...

Transforming Google Maps from using jQuery to AngularJS

If I have a Jquery google map with find address and routing system, my goal is to convert it to an angular google map with more options. The current Jquery google map code looks like this: var directionsDisplay = new google.maps.DirectionsRenderer({ d ...

Steering clear of repeating evaluations and dynamically unloading objects requested with `require` is important

I'm currently delving into the intricacies of the nodejs module system. Among the resources I've come across so far are: https://nodejs.org/api/modules.html These readings have shed light on a few aspects, but I still have some lingering ques ...

Is it possible to preserve the <canvas> elements to use for future animation frames?

Currently, I am working on a graph visualization project that involves complex calculations being done on an HTML5 canvas. My goal is to create an interactive animation where the graph remains fixed, but additional elements are overlaid as the mouse moves ...

Having trouble accessing AngularJS Modal dialog pop-up through clicking

I am trying to interact with a dialog box in Selenium Webdriver by clicking on the 'Yes' button. I have attempted to use Actions, window handles, and even switchTo.alert() method but haven't had any success so far. Here is a screenshot of th ...

Reveal a concealed div upon submitting an HTML form to display the resulting output

I have created an HTML form to gather information about a person's name and location. Once the user submits the form, I want the output to be displayed at the bottom of the page using PHP echo. My specific requirement is, To initially hide the outp ...

The angular ui-keydown feature is unable to detect the combination of shift, ctrl, alt, and A keys

As an illustration: <div ui-keydown="'shift-ctrl-alt-65': 'ctrl.scrollFromShortcut($event,\'others\')'"></div> It seems that shift-ctrl-65 is functioning properly, however, the issue arises when trying ...

Can the dashstyle be configured for a solid-gauge chart in Highcharts?

I am having trouble making the border dashed on my pie chart. It seems that the solution provided for solidgauge charts is not working as expected. Interestingly, the graph property is undefined for solidgauge charts. I wonder if the dashed style could be ...

Ways to eliminate existing information when conducting a search

Recently, I was tasked with integrating a search engine into a website that already has a list of data displayed on the first page. The challenge I faced was figuring out how to hide or remove this existing data when a new search request is made. You can v ...

javascript popup window with redirection functionality

Hello everyone, I need assistance with the code snippet below: echo ("<SCRIPT LANGUAGE='JavaScript'> window.alert('Successfully Updated') </SCRIPT>"); I am trying to redirect the page to my edit.php after c ...

Three.JS: Utilizing a wireframe material for spheres with the EdgesHelper control

I'm exploring Three.JS for the first time and I have some doubts about whether it's the best tool for my current project. My goal is to create a wireframe material on a simple spherical geometry that looks like this: https://i.sstatic.net/WPfAh ...