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

Is it necessary to close the navigation drawer after selecting an item?

Currently, I'm working on a project for my University where I am trying to incorporate a feature that will automatically close the navigation drawer whenever any of its items are clicked. However, I am facing some challenges figuring out how to achiev ...

The onBlur event attached to a div is triggered when transitioning from one input element to another within the same div

Here's a scenario: I have a div with two input fields nested inside, like this: <div> <input placeholder="Input1"/> <input placeholder="Input2"/> </div> I have a requirement to trigger a specific ...

Checking the efficiency of Graphql API

Currently, I am in the process of optimizing key features within my Node.js API which incorporates GraphQL. This API serves as a proxy, receiving requests from various sources and forwarding them to multiple APIs based on the request. I am interested in ...

Problems with WordPress Theme Rendering in Outdated Versions of Internet Explorer

Currently, I am developing a website for Chase on the Lake at http://chaseonthelake.com/. While everything looks perfect in FireFox, there are some display issues when viewing it in Internet Explorer. The dropdown transparency is not showing correctly, m ...

Converting a string to an HTML object in Angular using Typescript and assigning it to a variable

I am facing an issue with passing HTML content from a service to a div element. I have a function that fetches HTML content as a string from a file and converts it into an HTML object, which I can see working in the console. However, when trying to assign ...

AngularJS Service that handles several independent queries

I'm struggling with creating an AngularJS service that fetches data from multiple HTTP requests. Despite my efforts, I can't seem to get it working. The REST call flow is as follows: Get /index which returns an array of URLs Call each URL and ...

Encountering the "Cannot set headers after they are sent to the client" error within an Express.js application

In my recent project, I created a middleware to authenticate users and verify if they are verified or not. Initially, when I access protected routes for the first time, everything works fine and I receive success messages along with verification of the JWT ...

Utilizing Javascript to Open a New Tab from Drupal

I'm attempting to trigger the opening of a new tab when a specific menu link is clicked within a Drupal website. My initial approach was to incorporate JavaScript directly into the content of the page, but unfortunately this method has not been succes ...

What is the reason that Gatsby's arrow function is unable to access a value from props that is calculated from a promise?

Could someone shed light on why the key value is showing as undefined within the arrow function: // in parent component const Parent = () => { const [key, setKey] = useState<string>(); // this contains an expensive function we on ...

The wrapAll() method can be used to wrap list items within two columns

I am looking to group multiple li elements within two div containers by using jQuery's wrapAll method. The challenge lies in the fact that these items are rendered within a single <ul> element via a CMS. Here is the current setup: <ul> ...

Submitting a file to the Slack API via the files.upload method using jQuery

I'm attempting to upload a file on a webpage and send it to Slack using the Slack API. Initially, my code looked like this: var request = require('request'); $(".submit").click(function(){ request.post({ url: 'https://slack.co ...

Insert a new item into an existing list using jQuery

I am looking to enhance user experience by allowing them to easily add multiple sets of inputs with just one click. I have been experimenting with jQuery in order to dynamically insert a new row of input fields after the initial set. My current approach i ...

The Angular service "this" is altering the context of the window object

I must have made a mistake somewhere and I know I am overlooking something obvious. The aim is to create a service that provides basic authentication features such as login, logout, and checking if a user is logged in or not. Upon loading the page, I veri ...

Tips for Deactivating One Button While Allowing Others to Remain Active

Whenever the $order_status is marked as Accepted, only the button labeled Accept should be disabled. If the $order_status changes to Dispatched, then the button that should be disabled is labeled as Sent. However, if the status is Cancelled, then the butto ...

Learn how to dynamically modify the text and color of a column value within a <v-data-table> component in Vue.js 2.6.11 and Vuetify 2.2.11 based on a specific condition

In my current project where I am developing a web application using ASP.NET CORE for the backend and vue.js for the frontend, I encountered an issue with Vuetify's CRUD Datatable UI Component in a page named "Category". The problem arises when trying ...

I am interested in scraping a webpage, how should I go about it?

Similar Questions: How to create a web crawler? Top techniques for parsing HTML I've always been curious about accomplishing a task like this. Although I do not own or manage the website (), the information I am interested in is publicly acce ...

Implementing a filter function in Angular 2 and Ionic 2 that is dependent on *ngFor on a separate page

I recently created a simple ion-list along with a filter to display items based on a specific key:value pair. I'm not entirely sure if I've implemented it correctly, so any suggestions on a better approach would be greatly appreciated. LIST.HTML ...

Error alert: Object expected on OnClientClick in Microsoft JScript runtime

I was in the middle of a quick test when I encountered an error. At this point, I haven't implemented any C# code yet and my aspx code looks like this: <script language=javascript type="text/javascript"> function myOnClick() { ...

Selenium webdriver cannot find the element within the JavaScript code

await driver.findElement(By.id('closeBtn')).click(); or await driver.findElement(By.xpath('//*[@id="closeBtn"]')).click(); When attempting to use the above conditions for a pop-up, it does not work as expected. An error is ...

Creating a streamlined system for building and deploying an angularjs/asp.net web api

Looking to streamline the deployment process for my AngularJS app and C# WebAPI. The Angular app repo is stored in stash, while the C# REST API is in TFS. Is it feasible to set up an automated build and deployment system for this setup? What options are ...