What is the best way to duplicate a node in the Angular UI tree?

Looking to efficiently clone nodes in an Angular UI tree along with all their children?

I currently have an event click setup like this: ng-click="newSubItem(this)", where the function newSubItem is as follows:

$scope.newSubItem = function (scope) {

                var nodeData = scope.$modelValue;
                var childNodes = [];

                angular.forEach(nodeData.nodes, function (value) {
                    childNodes.push(value);
                });

                var totalNodes = nodeData.nodes.length;
                var prefixIncrement = totalNodes + 1;

                nodeData.nodes.push({
                    id: nodeData.id + prefixIncrement,
                    prefix: nodeData.prefix + "_" + prefixIncrement,
                    title: nodeData.title + '.' + (nodeData.nodes.length + 1),
                    value: nodeData.value,
                    type: nodeData.type,
                    nodes: childNodes
                });
            };

However, when attempting to insert all children from the cloned object into the new nodes: nodes: childNodes, it leads to numerous errors and disrupts the tree's structure.

Answer №1

The purpose of the newSubItem function is unclear as it does not return anything, leaving its intention ambiguous.

Instead of cloning objects, you are:

  • Creating references to objects (nodeData simply points to scope.$modelValue, meaning any changes to modelValue will reflect in nodeData) and
  • Constructing circular data structures (by pushing the array onto itself with arrr_nodes.push(arrr_nodes);),

Both of these actions may not align with your goals.

If you aim to deeply clone an object, Angular offers angular.copy() for this purpose. If you wish for nodeData to be an independent copy of modelValue, a simple solution would be:

$scope.newSubItem = function (scope) {
    var nodeData = angular.copy(scope.$modelValue);
    // Proceed to utilize nodeData as needed
}

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

Rails: Parameters are displayed in the console but cannot be accessed via params

I sent a get request to the following url: groups/:id.json Upon checking my Rails server console, this is the output: Processing by GroupsController#show as JSON Parameters: {"id"=>"11"} However, despite these parameters being passed, I am unable t ...

Can a single file in NextJS 13 contain both client and server components?

I have a component in one of my page.tsx files in my NextJS 13 app that can be almost fully rendered on the server. The only client interactivity required is a button that calls useRouter.pop() when clicked. It seems like I have to create a new file with ...

Is it possible to programmatically bind a click event to each individual word in a div element?

I'm attempting to link each word within an element without altering the markup inside the element using Javascript. ...

The Axios patch method encounters an issue where the baseURL is not retrieved

I have encountered a problem while trying to update the base URL in my Axios patch request. Despite specifying the new baseURL in the stageReceiver method, it continues to use the default baseURL (which is set when running npm serve). import axios from &q ...

AngularJS - Creating a Single Page Application with Routing and Templating

As a newcomer to angularJS, I find myself getting stuck on small questions related to setting up an internal routing service for protected files and routes. I would greatly appreciate any explanations or helpful links that could provide me with the missi ...

There was an error in parsing the JSON syntax while loading models using Three.js GLTFLoader

Discovering how to use Three.js has been an exciting journey for me, thanks to the tutorial available on discoverthreejs.com. Creating meshes and geometry through three.js is a breeze for me. However, things take a turn when I try to import models from B ...

Ways to center the percentage on the progress bar

I'm having an issue with positioning the percentage 100% in the center of the element. I attempted adjusting the spacing in the JavaScript code, but so far it hasn't been successful. Here is the current output for the code: http://jsfiddle.net/G ...

Want to achieve success with your AJAX calls in JavaScript? Consider using $.get

As I clean up my JavaScript code, I am looking to switch from using $.ajax to $.get with a success function. function getresults(){ var reqid = getUrlVars()["id"]; console.log(reqid); $.ajax({ type: "POST", url: "/api/ser/id/", ...

Understanding how to decode querystring parameters within a Django view

In the application I'm working on, there is a search form that utilizes a jQuery autocomplete plugin. This plugin processes the querystring and sends back the suggested item using encodeURI(q). For example, an item like Johnny's sports displays ...

A step-by-step guide on configuring data for aria's autocomplete feature

Currently, I am implementing aria autocomplete and facing an issue while trying to populate data from the server into the selection of aria autocomplete. I have tried setting the selected property of the aria autocomplete object, but it doesn't seem t ...

Angular displays error ERR_UNKNOWN_URL_SCHEME when attempting to retrieve an image saved in a blob

As I transition my app from Electron to Angular, one of my main objectives is to display an image uploaded by a user. Here's how I attempted to achieve this: page.component.ts uploadImageFile(){ fileDialog({}, files =>{ //Utilizing the fileDi ...

Creating a protective black outline around the content within an Electron application

When using electron to convert a video game created with Phaser 2 to a .exe file, I encountered some border or margin around my content. I attempted to resolve this issue by utilizing full screen mode and the useContentSize property, but unfortunately, th ...

An unexpected error occurred: [$injector:modulerr] ngAnimate AngularJS 1.2

Upon running my application, I encountered an Uncaught Error: [$injector:modulerr]. It seems that with the update to version 1.2 of AngularJS, certain functionalities have been removed from the core. I have downloaded angular-animate.js and all other exter ...

Can you explain the significance of polyfills in HTML5?

What exactly are polyfills in the context of HTML5? I've come across this term on multiple websites discussing HTML5, such as HTML5-Cross-Browser-Polyfills. Essentially, polyfills refer to tools like shims and fallbacks that help add HTML5 features ...

Transferring data from a stream in NodeJS to FrontEnd using ReactJS

How are you doing? I'm trying to figure out how to send a large data request from PostgreSQL to the FrontEnd in JSON format. Can anyone help with an example of how this can be achieved? Thank you. Here is my code: const express = require('expr ...

Is it possible to use JavaScript or jQuery to call a WCF Service and retrieve a collection of System.IO.Stream objects?

I am developing a WCF service that will be utilized by plain JavaScript on the client side, as well as some jQuery JavaScript. 1) How can I set up the plain client JavaScript to call the WCF Service in a manner that retrieves a collection of System.IO.Str ...

Is it possible to use JavaScript to manage multiple instances of the same form on a single webpage?

In my thumb gallery, I have implemented a functionality using ajax/javascript to seamlessly submit a form for each image to report it as broken. This form and script are templated, with the script located in the header and the form printed multiple times o ...

Set default date input in Ionic to be today's date

I'm currently developing a project using Ionic framework and I need to set a default date (which is today's date) on an input field. My code works perfectly when the input type is set to text, but it doesn't work if I specify the type as da ...

updating the HTML DOM elements using JavaScript is not yielding any response

One way that I am trying to change the background of a div is by using a function. Below is an example of the html code I am working with: $scope.Background = 'img/seg5en.png'; document.getElementById("Bstyle").style.background = "url("+$scope.B ...

Tips for implementing an image placeholder in an AngularJS project

I have a search input box and I want to change the placeholder text "Search here" to an image. Is this possible? code <input id="autoComplete" type="text" ng-model="selected" typeahead="task.name for task in taskList | filter:$viewValue | limitTo:20" ...