"Is there a way to eliminate an object from $scope without having to loop through the

I have a jsfiddle that you can check out here.

In the fiddle, we are able to add new nodes and delete all children in the parent node. However, my question is how can I delete a specific child without having to iterate through the array? I am aware that we have a method called Array.prototype.splice() that can be used for this purpose.

Array.prototype.splice()

If we want to remove a particular object like the one shown in screenshot #1, we can obtain its index and use the splice() method.

https://i.sstatic.net/RAwh2.png

But what if I want to remove a deeply nested object without iterating through the entire array for performance reasons?

https://i.sstatic.net/6IpvM.png

Currently, when I console.log, I only see:

Object { name: "Node-8-6-2", menu: false, $$hashKey: "object:151" }

This means I do not have direct access to the nodes of the parent array, and hence need to iterate through the entire array to remove it.

Does anyone have a solution to this problem?

Answer №1

Your updated Plunker can be found here: http://jsfiddle.net/marduke182/uXbn6/2828/

Key modifications include:

Including parent references to the object using parentNodes.


$scope.add = function(data) {
    var post = data.nodes.length + 1;
    var newName = data.name + '-' + post;
    data.nodes.push({name: newName, nodes: [], parentNodes: data.nodes});
};

Implementing a delete node method that removes the specified index from the parentNodes array:


$scope.delete_node = function(data, index) {
    data.parentNodes.splice(index, 1);
};

Adding the new method to the template:


<script type="text/ng-template" id="tree_item_renderer.html">
    {{data.name}}
    <button ng-click="add(data)">Add node</button>
    <button ng-click="delete(data)" ng-show="data.nodes.length > 0">Delete nodes</button>
    <button ng-click="delete_node(data, $index)" >Delete node {{$index}}</button>
    <ul>
        <li ng-repeat="data in data.nodes" ng-include="'tree_item_renderer.html'"></li>
    </ul>
</script>

Answer №2

When creating a hierarchy within your data structure, consider including a parent attribute in your arrays:

var parentNode = [];
var node = [];
node.parent = parentNode;
parentNode.push(node);

If you wish to delete the node, use the following code:

var index = node.parent.indexOf(node);
node.parent.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

Combining two arrays from the same collection in MongoDB to create a new field (similar to a Left Join in relational databases)

I have a unique assortment consisting of 2 arrays. One array contains fewer properties than the other, but they are connected through the 'Code' property. My goal is to create a third array that combines both arrays while ensuring distinct eleme ...

Angular will hold off until the subscribe operation has completed before passing values to another function

Here's a function I have in the code: File: subcategory.service.ts getSubCategoriesById(inp_subCatid: String): Observable<any>{ this.getSubCategoriesList().snapshotChanges().pipe( map(changes => changes.map(c => ({ key: ...

Unable to upload the file using AJAX

Here is my AJAX request where I am attempting to send form data to a PHP page and display messages accordingly. The problem I'm encountering is that when using serialize() method in AJAX, my file data is not being posted. As a result, the send.php scr ...

Launching a Nuxt.js Cloud Function

Is there a possibility to deploy a cloud function that allows for server-side rendering with Nuxt on Firebase? The issue lies in the fact that the Node version used on Firebase is 6.11.1 while the minimum required Node version for Nuxt versions 1 and above ...

Accessing class properties from JavaScript code

Can you retrieve the class values of a style element using Vue's script section? For example: .node-output02 { bottom: #{-2+$portSize/-2}px; left: #{$nodeWidth/3}px; } In the script, I'd like to achieve: const left = .node-output02. ...

Selecting a HEX code from a color picker to configure three.js as a string

Recently, I've been using a color picker from jscolor.com that outputs colors in the format of FFA6A6. The challenge I'm facing is integrating this color output with three.js, which requires the color to be in the format of 0xFFA6A6. As much as I ...

"Changing a Java script base addon file to a customized addon in Odoo 16: A step-by-step guide

Here is the JavaScript file located in the "documents" enterprise base addon: I want to include the field "document_type_id" in the export const inspectorFields = [] array through a custom addon. /** @odoo-module **/ import { device } from "web.confi ...

Tips for identifying truncated text when resizing the td element

While using the resize option in my table, I noticed that it cuts off some text. How can I determine the size at which the text begins to get cut off? https://i.sstatic.net/X7tKK.png This issue occurs when I resize the header https://i.sstatic.net/peycT. ...

Getting the value of an anchor tag in Laravel and utilizing it within an input field

I am facing an issue where $emp->id provides the correct id, but when I try to get id={{$emp->id}} it doesn't work as expected. Can someone please help me with this problem? <a href="{{'/employee'}}?id={{$emp->id}}" type="button ...

Refreshing the form fields and storing the information using AngularJS

I have successfully implemented a basic form using AngularJS. The issue I am facing is that even after the user enters their details and submits the form, the values remain in the input fields. My goal is to store the details of multiple fields in the con ...

Passing and removing array parameters in HTTP requests using Angular

I have an Array of statuses objects. Each status has a name and a boolean set to false by default. These represent checkboxes in a form with filters - when a checkbox is checked, the boolean value is set to true: const filters.statuses = [ { name ...

What is an alternative method to retrieve form data without relying on bodyParser?

When it comes to accessing posted form data without using bodyParser, what alternatives are available? How exactly does bodyParser grant access to the data in req.body? Additionally, I am curious about the inner workings of this process on a deeper level. ...

Wrapping up the HTML click design, throughout the extensive project

It seems like a common issue for developers working on projects with a large code base. We have multiple components that follow this specific pattern: $('#elm').on('click',function($e){ $e.stopPropagation(); //... do something ( ...

Steps for submitting a form using Bootstrap 4

Hi there! I'm struggling to get this form to function properly by sending data to my email address. I have included bootstrap.js, bootstrapjquery.js, and popper.js in my setup. I was hoping to find a solution within this code snippet that allows the ...

The Bootstrap Mobile Navigation transition is not displaying as intended in my CSS coding

On both desktop and mobile screen sizes, I have a white navigation bar. However, for the mobile dropdown menu, I want the background to be grey. I managed to achieve this by targeting .show on smaller screens in the CSS and specifying the grey background ...

Simultaneous appearance of multiple jQuery dialogs

As I work on creating a team page, each team member has their own div that contains a photo and employee information. My goal is to have a dialog box pop up when the photo is clicked, using the $this context to retrieve the employee data from the same div. ...

Creating a custom Jquery function to generate a Div element instead of a Textbox in your web application

I need assistance with a jquery function that retrieves data from a JSON PHP MySQL setup. The retrieved results are currently displayed in textboxes. function showData(wine) { $('#Id').val(wine.id); $('#question').val(wine.question ...

Accessing JSON data and populating a dropdown menu with JQuery

I am facing an issue with extracting values from a JSON array using jQuery. The structure of the array is as follows: [{ "": "Select your State/Region" }, { "BAL": "Balkh" }, { "BAM": "Bamian" }] Although I have attempted to loop through the array in ord ...

Renaming properties in an AngularJS model

After receiving the data in a structured format, my task is to present it on a graph using radio buttons. Each radio button should display the corresponding category name, but I actually need each button to show a custom label instead of the original categ ...

Angular.js, implementing form validation upon submission only

Is there a way to conduct form validation using Angular.js specifically upon submitting? I am looking to display error messages solely upon submission, similar to how it is done on this website: , without taking into account focus changes, etc. ...