如何在Angular UI树中克隆节点? [英] How to clone node in Angular UI tree?

查看:98
本文介绍了如何在Angular UI树中克隆节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用所有子项在Angular UI树中克隆节点?

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

现在我使用事件点击: ng-click =newSubItem(this )其中 newSubItem 是函数:

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

当我尝试将克隆对象中的所有子项插入到新的节点时:节点: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.

推荐答案

我不是很清楚你想在 newSubItem 函数中做什么 - 它没有返回任何东西,所以它的目的并不明显。

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


  • 复制对象引用( nodeData 只是对范围。$ modelValue 的引用,所以如果modelValue稍后更改,那么 nodeData )和

  • 创建循环数据结构(通过将数组推送到自身, arrr_nodes.push(arrr_nodes); ),

  • 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.

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

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
}

这篇关于如何在Angular UI树中克隆节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆