0

如何克隆 Angular UI 树中的所有子节点?

现在我使用事件点击:函数ng-click="newSubItem(this)"在哪里:newSubItem

$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
                });
            };

当我尝试将所有子对象从克隆对象插入到新对象时,nodes: nodes: arrr_nodes它会产生很多错误并破坏树。

4

1 回答 1

1

我并不完全清楚您在该函数中要做什么newSubItem——它不返回任何东西,所以目的是什么并不明显。

但你不是在克隆对象,而是在

  • 复制对象引用(nodeData只是对的引用scope.$modelValue,所以如果 modelValue 稍后更改,也会如此nodeData)和
  • 创建循环数据结构(通过将数组推到自身上,arrr_nodes.push(arrr_nodes);),

这两者都不是你想要的。

为了回答您提出的问题,如果您尝试对一个对象进行深度克隆,Angular 提供angular.copy()的正是这样做的。如果您的意图是nodeData成为 的克隆modelValue,您所需要的只是

$scope.newSubItem = function (scope) {
    var nodeData = angular.copy(scope.$modelValue);
    // presumably now you would do something useful with nodeData
}
于 2017-06-12T12:03:57.680 回答