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

Sort through an array containing JavaScript objects in order to filter out certain elements that match a different

Below is a fictional JavaScript array made up of objects: const permissions = [ { moduleEnabled: true, moduleId: 1, moduleName: 'Directory' }, { moduleEnabled: true, moduleId: 2, moduleName: 'Time off' } ...

What is the method for submitting a POST request with a JSON body that consists of only a string, without any key-value pairs included?

There was a developer who, not knowing the correct JSON format for key-value pairs, created a JSON body that looks like this: { "dog" } Instead of { "dog": "dog" } I must send the request from a JavaScript file, and the body needs to be in JSON f ...

Is there a way to apply an event function after adding elements through append?

When I click the button, a div is appended inside the body. However, I am trying to make it so that when I click on this newly appended div, an alert message pops up. I have tried implementing this with a highlighted area, but have been unsuccessful. How c ...

Vue.js filters items based on their property being less than or equal to the input value

I'm currently working on a project in vue.js where I need to filter elements of an object based on a specific condition. I want to only return items where maxPeoples are greater than or equal to the input value. Below is a snippet of my code: model ...

Modify the design of the button in the CSS code

I am facing an issue with the layout of the Visible Columns button and unable to standardize it like the buttons above using CSS enter image description here The code snippet for the Visible Columns button is as follows: import React, { useState, useEffe ...

Hover and hover-off functions in navigation menu

html <div class="hidden-nav"> <h4>lorem</h4> <ul class="decor-menu-list"> <li><a href="#">123</a></li> <li><a href="#">123</a></li> <li><a hre ...

Exploring timezones using moment.js

I have received scheduledTime and timezone data from an API, for example: scheduledTime: 1603890000000 timezone: "EDT" My goal is to display this information in the user's device timezone, such as CST. What would be the most effective approach to ach ...

ui-router: Converting URL parameters

Is there a way to seamlessly transform URL parameters? Let me illustrate with a scenario. Our URL structure is like this: /shopping/nuts/:productId /shopping/berries/:productId /shopping/juice/:productId The products in our app, fetched from an API, may ...

Verify the Ajax submission of a post request prior to transmitting any data

Currently, I am utilizing Google Tag Manager to handle form submission inside a Bootstrap modal. Due to limited backend access, I have opted for GTB to target a specific button and utilize the onClick event. <script> $(document).on('submit&apos ...

Bash Array Looping in a for statement

Is this the correct way to print out elements from the 13th element up until the second-to-last element of an array in BASH, even if I don't know the length of the array? for index in `seq 13 $(({myarray[@]-1))` do echo ${myarray[index]} done ...

I am in need of eliminating repetitive comments from each post

data structure can you help figure out what is causing the issue in this code that seems to be removing old comments? mutations:{ getPosts(state) { let unique = [...new Set(state.posts)]; for (let i = 0; i < uniq ...

Guide to properly deserializing a JSON string into a class with a nested List of different class members

I have a scenario where I am sending a JSON stringified "View" object from the browser to an ASP.Net Page Method using Jquery's $.Ajax(). The issue I am facing is that while the Javascript deserialization is successful for all the strings and integers ...

The 'v-model' directive necessitates a valid attribute value for the left-hand side (LHS)

I am facing an issue with my Vue application. I have a table where each row has its own unique id. I need to show or hide certain elements based on a condition in the v-model directive which compares the row id with a value in the model. The current code s ...

Issue with transmitting Razor form data to API controller using fetch or AJAX

I have created a basic razor web project and defined it as follows: in program.cs I added builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN"); In the controller, this is what I did: [Route("/api/[controller]")] [ApiCon ...

Tips for automatically closing all other divs when one is opened

I have multiple divs structured like this: <div id="income"> <h5 onclick="toggle_visibility('incometoggle');">INCOME</h5> <div id="incometoggle"> <h6>Income Total</h6> </div> </div> <d ...

Customizing data attributes for child components in Vue 2

In my Vue project, I have created a multi-page questionnaire using the v-show directive within a container called RiskAssessmentTest.vue. To handle loading questionnaire drafts, I have a component named RiskAssessmentDrafts.vue, which has the following st ...

JavaScript - Unable to Modify Select Value with Event Listener

It's interesting how I can change the selected option in a dropdown list using JavaScript without any issues. However, when I try to do the same thing within an event listener, the option does not seem to change. Here's the HTML code: <select ...

[.TextureUnitWarning] ALERT: Unit 1 is lacking a texture binding for rendering test.html:1

I've been attempting to incorporate texture into my project. var bumptexture = THREE.ImageUtils.loadTexture('grid.jpg'); var normaltexture = THREE.ImageUtils.loadTexture("normal.jpg"); var diffusetexture = THREE.ImageUtils.loadTexture ...

Update an API call to switch from promises to observables, implementing axios

Recently, I have been experimenting with using rxjs for API requests in a React application and this is the approach that I have come up with. What are your thoughts on this method? Are there any best practices that you would recommend following? If you ...

Error in hook order occurs when rendering various components

A discrepancy was encountered in React when attempting to render different components Warning: React has detected a change in the order of Hooks called by GenericDialog. This can result in bugs and errors if left unresolved. Previous render Next ren ...