Ways to remove items from an array within an AngularJS program

I'm currently working on a simple task: removing an item from my array.
The array is structured as follows:

myWordsInJSON = [{"eng":"frau","rus":"жена"},{"eng":"mann","rus":"муж"},{"eng":"witwe","rus":"вдова"},{"eng":"witwer","rus":"вдовец"},{"eng":"schwiegervater","rus":"свекор"}]

Below is the HTML code I am using:

<tr ng-repeat="item in myWordsInJSON">
          <td>{{$index + 1}}</td>
          <td>{{item[Params.lang1]}}</td>
          <td>{{item[Params.lang2]}}</td>
          <td><span class="label label-danger"
                         ng-click="cut({{$index}})">x</span>
          </td>
        </tr>

See output screenshot

Everything looks fine. However, when I click the 'delete' label, the cutting function in my Controller is triggered:

 $scope.cut = function(index){
  $scope.myWordsInJSON.splice(index,1);
  if ($scope.myWordsInJSON.length == 1)
    $scope.myWordsInJSON = [];
  console.log('cut, index =', index,$scope.myWordsInJSON);
};

But then something strange happens. After deleting a few items from the beginning of my array, I encounter this issue:

everything appears to be normal

The DOM still looks good, with the last element of my array displayed as:

<tr ng-repeat="item in myWordsInJSON" class="ng-scope">
          <td class="ng-pristine ng-untouched ng-valid ng-binding">2</td>
          <td class="ng-binding">schwiegervater</td>
          <td class="ng-binding">свекор</td>
          <td><span class="label label-danger" ng-click="cut(1)">x</span>
          </td>
        </tr>

HOWEVER!!! When I try to click on this element, which should trigger my cut function like cut(1), nothing happens and in the console I see

index = 4

This means that, instead of receiving index=1, my function is getting index=4

It seems like the initial page indexes are still present... How can I resolve this issue?

Update!

The problem was resolved by using '$index' instead of '{{$index}}'. Thanks to valverde93. But I still cannot understand why this occurred))) Perhaps someone can explain?

Answer №1

In a recent project, I came across a similar issue. The challenge stemmed from the discrepancy between the index of repeated elements and the actual index of the object in the array.

In order to resolve this issue, I implemented a solution where I passed the object's ID like so:

ng-click="deleteForId(repeatedElement.id)

Subsequently, within the deleteForId function, I searched for the object within the array to retrieve its index. Only then did I proceed to execute
$scope.myObj.splice(index, 1);

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

Avoiding Multiple Ajax Requests: Tips and Techniques

After spending 2 days trying to find a solution, it seems that StackOverflow does not have the correct answer for my issue. The problem involves having 2 ajax functions where the first one loads values onload: $.ajax({ url: 'http://localhost/movi ...

The standard TextField functionality was disrupted by the update to MUI v5

After typing a comment in the TextField and trying to click Done, nothing happens because the TextField still has focus. The first click removes the focus, while a second click is needed to complete the action. https://i.sstatic.net/XJvp0.png <TextF ...

What is the best way to define a function in React hooks - using a function statement or

When working with a react hook and needing to define a function inside it, which approach is preferable? useEffect(() => { //... function handler() {} //... }, []); or should I use the newer const declaration instead? useEffect(() => { ...

Encountering a "SyntaxError: Unexpected token '/' in... index.ejs while compiling ejs" issue following the recent npm package updates

After upgrading EJS from version 2.7.4 to 3.1.5 along with some other packages in my project, I am encountering a problem where I can no longer access any of the webpages. Instead, an error is being thrown on every page. Additionally, after the update, I s ...

Develop a unique splitter code that utilizes pure javascript and css, allowing users to drag and drop with precision

I am facing an issue with setting the cursor above my drop panel, as it results in a flicker effect. How can I set the cursor for my example to work properly? I have tried multiple different approaches to make this work. Although I am using the provided ...

Filter an array of objects based on criteria from another array

CustomArray.prototype.erase = function() { var target, args = arguments, length = args.length, index; while (length && this.length) { target = args[--length]; while ((index = this.indexOf(target)) !== -1) { this.splice(index, 1); ...

Dealing with event function inside object property: What's the best way?

Hello, I am currently using bootstrap-table for a web application where I need to redirect to another URL when a table row is clicked. The "onRowClick" events are managed through an object attribute known as onRowClick, where you assign it a function that ...

The folder path of the Nodes Express App.Route is causing confusion for other users

When utilizing Nodes.js Express for my routing, I encountered an issue. Normally, localhost:8080/Order works fine. However, when trying to use the GET method with the ID parameter like localhost:8080/Order/ID-12345 and proceeding to ViewOrder.html to execu ...

Angular Datepicker MinDate function prevents selection of dates "behind" by one

I've encountered an issue with the Angular Bootstrap Datepicker where I'm setting the min-date attribute as follows: <input type="text" class="" uib-datepicker-popup="MM/dd/yyyy" show-button-bar="false" ng-model="vm.date" ng-change= ...

Combining values with identical keys in a PHP MySQL D3 data set

Is there a way to convert data from a MySQL database into a D3 line chart? I have the following data: [{"key":"Branch1","values":["21","1961"]},{"key":"Branch2","values":["21","1961"]},{"key":"Branch2","values":["22","20040"]}] And I want to transform i ...

Tips for representing entire months as object keys using numerical values

Currently, I find myself a bit puzzled as to why my code is not functioning as expected, and I am hopeful that you all could assist me in solving this issue. The data structure I am working with consists of years and corresponding months. chosenMonths = { ...

Accessing public static files in Express by using the routes folder

I'm currently facing an issue with accessing a static file named 'home.html' located in the public directory of my app's architecture: public home.html routes index.js views myapp.js In myapp.js: var express = require('ex ...

list of key combinations in a ul element

I programmed a list of world states in PHP using an unordered list (<ul>): $WORLD_STATES = array( "France", "Germany", "Greece", "Greenland", "United Kingdom", "United States", "Uruguay" ...

Removing elements based on the size of the display

I need assistance with a JavaScript issue. I have a table with 2 rows and 5 columns, each column representing a day of the week with a specific class. The goal is to detect the current day based on the browser's width/height and remove all elements in ...

What is the best way to display nested JSON in JSX within a React Native application?

I need help with rendering nested JSON inside my JSX. Below is the JSON response: [{ "data": { "total_students": 13, "seats": "", "categories": [{ "id": 28, "name": "Economy", "slug": "econom ...

What is the process for downloading files in React from a Node server?

Backend setup for file download: router.get('/download/:fid', filesControllers.downloadFile); Here is the function defined in filesControllers.js to handle file download: const downloadFile = async (req, res, next) => { const fileId = req.p ...

Using the useQuery() function in a Next.js React app successfully fetches data from the API on the client side, yet the same API call fails to work when implemented in getServerSideProps on

I am attempting to retrieve data from the backend server using React Query within Next JS getServerSideProps. Here is the function used to fetch the data: export const getGoogleAuthUrl = async () => { const res = await fetch(`${process.env.NEXT_PUBLIC ...

What is the best way to constrain an input to specific values without relying on checking keycodes or experiencing any flickering of the value

Using vue, I am looking for a way to restrict user input in an input field based on a regex pattern. I am unsure of how to achieve this. Can someone please assist me? Here is what I have tried so far: codepen.io/assassin129/pen/yGZQWe ...

What is the origin of the term "res" in a NodeJS http request handler function?

In many NodeJS applications, the following code pattern is commonly used: const express = require("express"); const app = express(); app.post("/some-route", (req, res) => { const data = req.body; } I am puzzled by the ...

How do I obtain the array index ID in Vue.js?

Here's the scenario: I have an array with 4 objects and I need help displaying the index of the array. Can someone assist me with this? https://i.sstatic.net/yjcSW.png https://i.sstatic.net/rbTwl.png ...