0

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) {
                    arrr_nodes.push(arrr_nodes);
                });

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

                nodeData.nodes.push({
                    id: nodeData.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.

5
  • docs.angularjs.org/api/ng/function/angular.copy Commented Jun 11, 2017 at 21:30
  • Can you explain me, why input field in example is working, but by me is not? Commented Jun 11, 2017 at 22:11
  • Angular.copy makes a deep clone of the object, it looks like your code is just copying in references to the original arr_nodes. Commented Jun 12, 2017 at 10:43
  • Can you share an example please Commented Jun 12, 2017 at 10:49
  • ok, see below... Commented Jun 12, 2017 at 12:06

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.