Table order is requested, but the index fails to comply

I am facing an issue with sorting and deleting data from a JSON table. Even after sorting the columns, clicking "Delete" removes the wrong entry because the $index is not updated properly.

Here is the JavaScript code I am using:

  $scope.friends =
      [{name:'John', phone:'555-1212', age:10},
       {name:'Mary', phone:'555-9876', age:19},
       {name:'Mike', phone:'555-4321', age:21},
       {name:'Adam', phone:'555-5678', age:35},
       {name:'Julie', phone:'555-8765', age:29}];
  $scope.predicate = 'age';
  $scope.reverse = false;
  $scope.order = function(predicate) {
     $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
     $scope.predicate = predicate;
  };
  $scope.delete = function (friend, index) {
        $scope.friends.splice(index, 1);
  };

And here is the HTML code snippet:

 <table class="friend">
    <tr>
      <th>
        <a href="" ng-click="order('name')">Name</a>
        <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
      </th>
      <th>
        <a href="" ng-click="order('phone')">Phone Number</a>
        <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
      </th>
      <th>
        <a href="" ng-click="order('age')">Age</a>
        <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
      </th>
    </tr>
    <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
      <td>{{friend.age}}</td>
      <td><button ng-click="delete(friend, $index)">Delete</button></td>
    </tr>
  </table>

You can also check out the Plunker example by following this link:

http://plnkr.co/edit/iFIRQisV3qU21PFtMJdC?p=preview

Answer №1

Just made some modifications to your function in the updated plunker.

Wait until you have the object before using $index. Utilize the object instead.

    $scope.remove = function (item) {
        $scope.items.splice($scope.items.indexOf(item), 1);
    };

This should get the job done.

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

Having trouble starting Chrome during the second step of the AngularJS tutorial? Encounter an EIO error message preventing

My computer is running Windows 7 32-bit. I encountered an error when testing the AngularJS tutorial in step 2. Chrome fails to start with the following error message: --- versions --- AngularJS: 1.0.2 testacular: 0.4.0 --- messages ---- ...

How to verify if both MySQL queries in Node.js have fetched results and then display the page content

Seeking assistance with two queries: one to verify user following post author and another to check if the user has liked the post. I attempted to use the logic: if ((likes) && (resault)), but it's not yielding the desired outcome. After inve ...

Using JavaScript, generate an array of objects that contain unique values by incrementing each value by 1

I have an array of objects called arrlist and a parameter uid If the property value has duplicate values (ignoring null) and the id is not the same as the uid, then autoincrement the value until there are no more duplicate values. How can I achieve the a ...

Distributing actions within stores with namespaces (Vuex/Nuxt)

I'm encountering an issue with accessing actions in namespaced stores within a Nuxt SPA. For example, let's consider a store file named "example.js" located in the store directory: import Vuex from "vuex"; const createStore = ...

Avoid reloading the header component along with its APIs when navigating routes in React JS

I'm currently working on a web application using react js/next js and within it, I have various pages that make use of globally shared components like the Header and Footer. However, I am facing an issue where I want to prevent unnecessary re-renders ...

Can anyone suggest a method for adding comments and improving the organization of a bower.json file?

Managing a large project with numerous bower dependencies can be challenging. It's often unclear whether these dependencies are still being used or if the specified versions are necessary for a reason. It would be ideal to have the ability to add comm ...

JavaScript: Generating multiple variables using a for loop?

Is there a way to dynamically create n variables a_1, a_2, a_3 ... a_n, where the value of n is determined during runtime? Attempting to use the following code would not produce the desired outcome: var n = prompt("Enter number of variables?"); for (i= ...

Issue with popup display in React Big Calendar

I'm currently working on a calendar project using React-Big-Calendar, but I've run into an issue with the popup feature not functioning properly. <div className={styles.calendarContainer} style={{ height: "700px" }}> <C ...

Encountering issues with the hyperlink tag '<a>' in an HTML document

I've encountered an issue with the code on my HTML page: <body> <div align="center"> <a href="../index.html"> <img border="0" src="banner1.jpg" width="800" height="120" alt="Ecommerce Knowledge Base"> &l ...

"Enhabling tablesorter pagination to ensure that buttons always stay in sync with

I am experiencing an issue with the pagination buttons staying at the bottom of my page, even when there are only 2 entries left on the last page. Check out my table here: Is there a way to make the pagination buttons dynamically move to the top based on ...

Tips for excluding specific codes from running in BeforeAll for a specific Describe() block in Jasmine

Currently, I am in the process of writing a Jasmine unit test spec. The JS file contains several describe() blocks. Within the BeforeAll function, my objective is to execute a function only for the "A" and "C" Describe-Blocks. How can this be accomplished ...

Verification of Radiobox Groups in AngularJS

Could you please help me with validating a radiogroup using AngularJS, which is instantiated within an additional directive? The validation requirement is that the User must not be able to submit unless one of the radio buttons has been selected. This is ...

AngularJS: Refresh array following the addition of a new item

After saving an object, I am looking to update an array by replacing the conventional push method with a custom function. However, my attempts have not been successful so far. Are there any suggestions on how to rectify this issue? app.controller("produ ...

Animating jQuery Counter with Changing Background Color

I've implemented a Counter that counts from 0 to a specified number, and it seems to be working perfectly. However, I want to add an animation where the background color of a div height animates upwards corresponding to the percentage of the counter. ...

JavaScript's "for of" loop is not supported in IE 11, causing it to fail

Here is a piece of code I'm using to select and remove a d3.js node: if (d.children) { for (var child of d.children) { if (child == node) { d.children = _.without(d.children, child); update(root); ...

The server sends a response with a MIME type that is not for JavaScript, it is empty

I am trying to integrate an angular application with cordova. Upon running "cordova run android" and inspecting it in Chrome, the console displays the following message: "Failed to load module script: The server responded with a non-JavaScript MIME t ...

Is it possible to run Next.js 13 with React.js version 17?

Can Next.js 13 be used with React version 17? I upgraded my Next.js to version 13 and encountered a minimum requirement of React version 18, which is not compatible with my codebase. Is it possible to use Next.js 13 with React version 17 instead? ...

What sets apart toBeInTheDocument from getBy* in @testing-library/react?

Can you distinguish between these two methods in react-testing-library? expect(screen.queryByText('<something>')).toBeInTheDocument(); And screen.getByText('<something>'); (The specific getBy* and queryBy* operation are no ...

Eliminating an element from an array depending on the value of its properties

I need to remove an object from my List array by matching its properties value with the event target ID. Currently, I am using findIndex method to locate the index ID that matches the event.target.id. Below is an example of one of the objects in my list a ...

Issue with Node.js OAuth authentication

As someone new to Node.js and specifically OAuth, I have been exploring the use of Google APIs with Node.js. So far, here is what I've accomplished: var fs = require('fs'); var readline = require('readline'); var google = require( ...