In a peculiar occurrence, the behavior of array.splice is exhibiting unusual characteristics within an

Be sure to take a look at this plunkr for reference:
http://plnkr.co/edit/FQ7m6HPGRrJ80bYpH8JB?p=preview

I'm encountering an issue where, after adding an element and then deleting it from the array using the splice method, everything becomes disorganized.

code

Answer №1

In order to use the <code>splice function with an array, it's important to pass in a valid array index. The issue in your code is that you are passing ngModel.index to the removeNode function and using it as the index to splice the array, which is not the correct array index.

To resolve this problem, you should iterate through the elements of the array and check the index property of each element to find the actual index. In my example, I used angular.forEach, where the second parameter provides the real index of the array element.

Here is the corrected code:

$scope.removeNode = function(index) {
    var foundIndex;
    angular.forEach($scope.sitemap, function(value, idx){
        if(value.index === index)
            foundIndex = idx;
    })

    $scope.sitemap.splice(foundIndex, 1);
}

Check out the Demo Here

Answer №2

When you create a new object, you assign a hardcoded index value of "abc" to each object.

var abc = 0;
$scope.addNode = function(){
    abc++;
    var addObj = {name:"name"+abc, index:abc};
    $scope.sitemap.push(angular.copy(addObj));
}

Subsequently, when you remove an object, you use this hardcoded index value in the function.

$scope.removeNode = function(index){
    $scope.sitemap.splice(index,1);                     
}

For instance, if you have the following array:

obj1 - hardcoded index 0 - array index 0
obj2 - hardcoded index 1 - array index 1

If you remove obj1 from array with index 0, obj2 will take its place at index 0 in the array, like so:

obj2 - hardcoded index 1 - array index 0

However, even though the actual index has changed, you are still passing index 1 to the removeNode function as it was created with that value.

Answer №3

Here is an alternative solution I recommend: Demo

In my perspective:

  • sitemap should not be defined within the current directive (sample), as it belongs to a list item and not the list itself.

  • Additionally, you have an addNode method in your controller. It would be beneficial to also include a removeNode method.

You can access the controller's methods within the directive using

removeAction: '&removeAction',
:

scope: {
    ngModel: "=ngModel",//or "="
    removeAction: '&removeAction',//or "&"
  },
  controller: ["$scope", function($scope) {
    $scope.removeNode = function(item) {
      $scope.removeAction({
        item: item
      });
    }
  }],

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

What is the best way to refresh my useEffect hook when a State change occurs in another component's file in ReactJS?

Seeking to execute an API call within useEffect() and aiming for the useEffect() function to trigger every time new data is appended to the backend. To achieve this, a custom button (AddUserButton.js) has been created to facilitate adding a new user to the ...

Store the information retrieved from an Ajax call regarding an artist on the page, ensuring that it is only saved once for that

I have been working on a single-page application that utilizes the Spotify REST API and JQuery to enable users to search for an artist and display their information on the page. However, I want to ensure that the app saves details about each artist only ...

`Developing reusable TypeScript code for both Node.js and Vue.js`

I'm struggling to figure out the solution for my current setup. Here are the details: Node.js 16.1.x Vue.js 3.x TypeScript 4.2.4 This is how my directory structure looks: Root (Node.js server) shared MySharedFile.ts ui (Vue.js code) MySharedFi ...

Create a selection menu in an HTML dropdown list using unique values from a JSON object that is separated by commas

I'm working with a JSON object that contains multiple key value pairs, one of which is the Languages key. This Languages key holds comma-separated values such as "English, Hindi, French," and so on. My goal is to extract distinct values from the Lang ...

"Internet Explorer text input detecting a keyboard event triggered by the user typing in a

It appears that the onkeyup event is not triggered in IE8/IE9 (uncertain about 10) when the enter button is pressed in an input box, if a button element is present on the page. <html> <head> <script> function onku(id, e) { var keyC = ...

Using v-model to dynamically update the router based on certain conditions

Check out this demo showcasing a navigation menu with nested items. Clicking "more" reveals the expanded list, which can be set to always open using v-model="item.model" with model = true. My goal is to have the submenu stay open only when the user is on ...

Instructions for linking a directive in Angular JS to a model containing keys that are generated dynamically

Imagine having a scope object defined like this: $scope.user = { pets : {} } and an element structured as follows: <my-pets id="pets" my-model="user.pets" data-title="Pet name" data-types="dog, cat, bird, hamster, exotic"> & ...

Transferring binary fragments to Node.js for assembly into a complete file. Creating a file

Hey there, I'm in a bit of a bind. I'm trying to send file chunks using multiple XMLHttpRequest requests and then receive these parts in Node.js to reconstruct the original file from the binary data. The issue I'm facing is that the final f ...

Please optimize this method to decrease its Cognitive Complexity from 21 to the maximum allowed limit of 15. What are some strategies for refactoring and simplifying the

How can I simplify this code to reduce its complexity? Sonarqube is flagging the error---> Refactor this method to reduce its Cognitive Complexity from 21 to the allowed 15. this.deviceDetails = this.data && {...this.data.deviceInfo} || {}; if (th ...

Is it possible to exclusively target a child div using JavaScript in CSS, without affecting the parent div?

I'm in the process of developing a calendar feature where users can select a specific "day" element to access a dropdown menu for time selection. The functionality is working fine, but I've encountered an issue. When a user selects a time from th ...

Updating Vue component property when Vuex store state changes: A step-by-step guide

As I work on developing a straightforward presentation tool using Vue js and Vuex to manage the app state, I am facing a challenge in implementing a feature that tracks changes in the presentation such as title modifications or slide additions/removals. Cu ...

Issues with the initial drop functionality in jQuery UI

How come the jQuery code does not work properly on the first drop? $(".drag").draggable({ revert: 'invalid', drag: function(event, ui) { $(this).addClass('valid'); } }); $("#droppable").droppable({ accept: '.valid&apos ...

What is the best way to position the left sidebar on top of the other components and shift them to the

Currently, I am working on a project to display NBA data fetched from an API. I am aiming to recreate the design showcased here: Dribbble Design My main challenge lies in overlaying the left sidebar onto the main box and shifting the components sligh ...

In PHP, extract the initial three characters from each item within a foreach loop

In the following code snippet, I am trying to extract data from a JSON array and store it in a variable: $arr = json_decode($jsondata, TRUE); $arr2 = $arr['items']['item']; echo '<ul>'; foreach ($arr2 as $val) { echo &a ...

Unable to establish communication with server. Facing issues in connecting AngularJS with NodeJS

I am currently working on establishing a communication process between my server and client to receive either a "success" or "failure" response. The server is being developed using node.js with the express framework, while the client is built using angular ...

I am experiencing issues with the button click functionality in my Google extension

Greetings! I am currently developing a Chrome extension that will automatically redirect to my website and fill in the password. However, I am facing an issue with submitting the button click event. // Here is my manifest.json code { "name": "z", "v ...

Accessing the observable's value by subscribing to it

There is a defined observable called imageOptions$ in my code: imageOptions$: Observable<BoundImagesToProject[]> = this.imagesService .getBoundImages({ projectId: this.projectId }) .pipe(map((images) => (images.data))); and it is used in the temp ...

Building a Dynamic CSS Grid

Today is the first time I'm reaching out for help rather than figuring things out on my own. I'm currently working on a website layout that consists of visible tiles all with equal sizes, forming a grid structure. The challenge I face is making t ...

Dynamic horizontal scrolling

I need help implementing a site using React that scrolls horizontally. I'm unsure how to implement certain aspects, so I am looking for some assistance. Within a wrapper, I have multiple container Divs. <div class="wrapper"> <div class=" ...

Adding Multiple Items to an Express Endpoint

I have a requirement to store multiple objects in my mongo database within an express route. Currently, the process is smooth when I post individual objects (such as ONE casino), as shown below. Instead of repeating this numerous times, I am seeking assist ...