How to clone node in Angular UI tree?

折月煮酒 提交于 2019-12-19 11:44:15

问题


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.


回答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
}


来源:https://stackoverflow.com/questions/44488931/how-to-clone-node-in-angular-ui-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!