js展开一颗树

 

Tree View 指令不支持 树结构数据源, 只支持单层数组。(也许是我没发现,人家可以设置) 。我只能把树展开,变成单层数组。然后还要记录已经递归到第一层了。比如这样。

<!doctype html>

<html lang="en-US">

<head>

    <meta charset="UTF-8">

    <title></title>

</head>

<body>

<script type="text/javascript">

    var self = this;

    self.list =  [

        {

            "id": 1,

            "title": "node1",

            "children": [

                {

                    "id": 11,

                    "title": "node1.1",

                    "children": [

                        {

                            "id": 111,

                            "title": "node1.1.1"

                        }

                    ]

                },

                {

                    "id": 12,

                    "title": "node1.2",

                    "children": []

                }

            ]

        },

        {

            "id": 2,

            "title": "node2",

            "nodrop": true,

            "children": [

                {

                    "id": 21,

                    "title": "node2.1",

                    "children": []

                },

                {

                    "id": 22,

                    "title": "node2.2",

                    "children": []

                }

            ]

        },

        {

            "id": 3,

            "title": "node3",

            "children": [

                {

                    "id": 31,

                    "title": "node3.1",

                    "children": []

                }

            ]

        }

    ];

    function flatten (arr,level){

        var result = [],

                recursion = function (arr,level) {

                    arr.level = arr.level || level || 0;

                    //这里用了个巧妙的方法,记录该数组的level。有就用它自己的,没有就判断是不是别人给它的,别人给的一般代表自己是子树。然后给的时候 +1

                    arr.forEach(function (item) {

                        item.$$treeLevel =  arr.level;

                        result.push(item);

                        item.children && recursion(item.children,arr.level + 1);

                    });

                    delete arr.level;

                };

        recursion(arr);

        return result;

    };

    self.arr = flatten(self.list);

    console.log(self.arr);

</script>

</body>

</html>

web前端免费学习资料,搜【WEB前端互动交流群】

posted @ 2016-12-30 10:19  CC大神01  阅读(136)  评论(0编辑  收藏  举报