How to clone node in Angular UI tree?

How to clone node in Angular UI tree with all children?

Now I use event click: ng-click="newSubItem(this)" where newSubItem is function:

$scope.newSubItem = function (scope) {

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

                angular.forEach(nodeData.nodes, function (value) {

                var total_nodes = nodeData.nodes.length;
                var prefix_increment = total_nodes + 1;

                    id: + prefix_increment,
                    prefix: nodeData.prefix + "_" + prefix_increment,
                    title: nodeData.title + '.' + (nodeData.nodes.length + 1),
                    value: nodeData.value,
                    type: nodeData.type,
                    nodes: arrr_nodes

When I try to insert all children from cloned object to new nodes: nodes: arrr_nodes it gives a lot of errors and breaks tree.



I'm not entirely clear on what you're trying to do inside that newSubItem function -- it doesn't return anything, so it's not obvious what the purpose is.

But you're not cloning objects, instead you're

  • copying object references (nodeData is just a reference to scope.$modelValue, so if the modelValue changes later on so will nodeData) and
  • creating circular data structures (by pushing the array onto itself, arrr_nodes.push(arrr_nodes);),

neither of which is probably what you want.

To answer your stated question, if you're trying to make a deep clone of an object, Angular provides angular.copy() which does exactly that. If your intent is for nodeData to be a clone of the modelValue, all you need is

$scope.newSubItem = function (scope) {
    var nodeData = angular.copy(scope.$modelValue);
    // presumably now you would do something useful with nodeData


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.