The splice function in Angular is mistakenly removing a different record instead of the intended one that was

An issue with the Angular splice function is causing it to delete the wrong record. Here is the code snippet in question.

Within the code below, when attempting to delete the record labeled "Pat," the code ends up deleting the record labeled "Max." Please review the code snippet provided.

function CustomerController($scope) {
    $scope.list = [
        { ID:"1", FirstName: 'Bharani', LastName: 'Kumar', City: 'New Delhi' },
        { FirstName: 'Pat', LastName: 'J', City: 'Paris' },
        { FirstName: 'John', LastName: 'P', City: 'Washington DC' },
        { FirstName: 'Max', LastName: 'X', City: 'London' }
    ];
 
$scope.delCustomer = function (FirstName) {
     var index = $scope.list.indexOf(FirstName);
 $scope.list.splice(index, 1); 
    };
}
<!DOCTYPE html>
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">
</script>
</head>
<body>
    <div data-ng-controller="CustomerController">
        <ul>
            <li ng-repeat="item in list | filter:FirstNameSearch | orderBy:'FirstName':false">{{ item.FirstName +"  , "+ item.LastName +"  , "+ item.City}}      &nbsp;&nbsp;<a ng-click="delCustomer(item.FirstName)">Delete</a></li>
        </ul>
</div>
    <script src="CustomerController.js"></script>
</body>
</html>

Answer №1

Always make sure to send the entire record to the function instead of just the FirstName. This way, the function can properly match the first name with an array of records and return the correct index.

function CustomerController($scope) {
    $scope.list = [
        { ID:"1", FirstName: 'Bharani', LastName: 'Kumar', City: 'New Delhi' },
        { FirstName: 'Pat', LastName: 'J', City: 'Paris' },
        { FirstName: 'John', LastName: 'P', City: 'Washington DC' },
        { FirstName: 'Max', LastName: 'X', City: 'London' }
    ];
 
$scope.delCustomer = function (FirstName) {
     var index = $scope.list.indexOf(FirstName);
 $scope.list.splice(index, 1); 
    };
}
<!DOCTYPE html>
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">
</script>
</head>
<body>
    <div data-ng-controller="CustomerController">
        <ul>
            <li ng-repeat="item in list | filter:FirstNameSearch | orderBy:'FirstName':false">{{ item.FirstName +"  , "+ item.LastName +"  , "+ item.City}}      &nbsp;&nbsp;<a ng-click="delCustomer(item)">Delete</a></li>
        </ul>
</div>
    <script src="CustomerController.js"></script>
</body>
</html>

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

Verification of custom data type validation

I am puzzled by the behavior of this custom type state: interface DataType { [key: string]: string;} const [data, setData] = React.useState<DataType>({}); When I attempt to execute console.log(data === {}) It surprisingly returns false. Why ...

When updating the HTML content, JavaScript is outputting the code as text instead of running it

I am encountering an issue with adding the body content of a JSON file, which contains HTML code, to my existing HTML. Instead of executing the code, it appears as text within paragraph or header elements. I have searched through various discussions but ha ...

Run the jQuery script once it has been successfully loaded using jQuery's .load method

On the Index.html page, there is a select box labeled #choose_content_to_load and a div named #get_loaded_content <select id="choose_content_to_load"> <option>Some content from the page content.html and div #content</option> </select ...

Issue with improper lighting on Three.Geometry objects when using LambertMaterial in Three.js

After enhancing my initial version of this inquiry (previously asked question) with a JSFiddle showcasing the latest build of Three.JS and illustrating the lighting issue on Three.Geometry, I encountered difficulties with dependencies in Stack Snippets. Ho ...

Ways to create an object based on another object

Currently, I am teaching myself Javascript. My focus is on working with Vuejs and express for a CRUD App. In one of my components, I retrieve data from my backend using the API: localhost:3000/api/transport. The response contains all objects from the data ...

Unable to use addEventListener on media queries exceeding 768px

When testing the site on Firefox 49 and Chrome 63, I encountered the same issue. Clicking on each card worked fine on iPhone4, Galaxy 5, and iPhone 8 using Chrome. However, after switching orientations from 640px to 320px portrait view, the top card would ...

Unusual AngularJS Service Function Styling

I previously inquired about a similar issue, but unfortunately did not receive any correct answers. The query pertains to the service function in AngularJS. Interestingly, when I defined an AngularJS service using the service function in an unconventional ...

The JQuery .ajax() function is not functioning properly, although the success method is still executing

Having issues with an ajax call on a webpage. The WebMethod is working fine. Potential problem - ajax method called from UserControl embedded in a content page within a master page, accessible only after .Net authentication. Including this info for transp ...

Using ES6, one can filter an array of objects based on another array of values

Seeking assistance with creating a function to filter an array of objects using another array as reference values. For example: The array containing objects: const persons = [ { personId: 1, name: 'Patrick', lastName: 'Smit ...

The attempt to compress the code from this particular file within the node_modules directory was unsuccessful

Hey there! I'm facing an issue while attempting to compile my React project using npm run build. Upon running this command in the console, I encountered the following error message: Failed to minify the code from this file: ./node_modules/react- ...

The canvas appears blank when using Firefox version 36

The application is made up of an interface (html) and workspace (canvas). We utilize three.js to create elements on the canvas. So far, it's been functioning perfectly on Chrome, Opera, and Firefox 35. You can see it in action here: However, in Firef ...

Issues (forEach@, loadModules@, createInjector@, workFn@) encountered while conducting tests on $controller enhancement

I have applied a decoration to the controller named "originalCtrl" through the $controller service: //module declaration angular.module('decorationModule', [ 'originalModule', 'ExternalService' ]) //de ...

Generating dynamic dropdown menus in PHP

I'm currently working on a project that involves creating dynamic drop down lists in PHP using JavaScript. I've managed to fetch the value from the first dropdown list and display the corresponding values in the second list. However, the second l ...

Ensure to include Express validator version 6.4.0 in conjunction with express upload to verify the input data before proceeding with a POST request on the specified

Currently, I am facing a challenge in validating inputs, including an image upload, using express-validator and express-upload to parse multipart data. My goal is to validate the file being uploaded as an image or allow for no image upload. Despite followi ...

Discovering the technique to unearth a specific value within an array nested within another array

I am encountering an issue with finding a value in one array inside another array and utilizing the resulting value to update the state using setState(). Here is the initial state: this.state = { initialStudents:[ {name:"str1",tags;["str","s ...

Leveraging an AngularJS service within Angular framework

I am trying to incorporate an AngularJS service into my Angular project. Below is my main.ts file: import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {AppModule} from './app/app.module'; import {UpgradeMo ...

UI Router seamlessly loading all views

My UI router is functioning as intended, but I've noticed that when it loads a new view, it briefly displays all other views in that state before quickly removing them. What could be causing this behavior? EDIT: Upon further inspection, there is inde ...

What's the purpose of clicking on the page number before accessing the information?

After successfully rendering filtered products, I encountered an issue with implementing pagination. The pagination is functional but requires clicking on a page number before it displays correctly. Even though I have included a loading state, it's no ...

The Vue component does not render the JS Promise and instead displays it as

After setting up a promise that will be returned once a correct event is called with the correct action, I have the following code: import {EventBus} from "./EventBus"; export function completed() { EventBus.$on('queue-action', e => { ...

Challenges encountered when redirecting users with a combination of javascript and php

I have a login form that triggers a JavaScript function upon submission. This function calls a PHP page to process the input. The issue I'm facing is with how the redirections are displayed based on the user's role type. It attempts to display t ...