天天看點

tree架構疊代-angularjs

在html中出現很多如組織架構,崗位架構,或者多層菜單式的具有上下級關系的樹形菜單。

在用angularjs中碰到一個問題,用1.4.3版本會出現堆棧溢出問題,而1.6.2~1.7.0不會有問題。有其他更好的的疊代方式還不知道怎麼使用。

以下代碼是在基于angularjs1.7.0實作的,擷取到的資料格式是數組。

在控制器中實作,也可以放到指令中。

/**
         * json轉tree格式
         * @param a
         * @param idStr
         * @param pidStr
         * @param chindrenStr
         * @returns {Array}
         */
        $scope.transData = function(a, idStr, pidStr, chindrenStr) {
            var r = [], hash = {}, id = idStr, pid = pidStr, children = chindrenStr, i = , j = , len = a.length;
            for (; i < len; i++) {
                hash[a[i][id]] = a[i];
            }
            for (; j < len; j++) {
                var aVal = a[j], hashVP = hash[aVal[pid]];
                if (hashVP) {
                    !hashVP[children] && (hashVP[children] = []);
                    hashVP[children].push(aVal);
                } else {
                    r.push(aVal);
                }
            }
            return r;
        };
        /*
        *通過接口擷取到的treeObj對象内容轉成具有層級結構的樹。
        */
    $scope.jsonDataTree = $scope.transData(treeObj, 'id', 'parentId', 'children');
           

在頁面中的指令内容

<body>
    <div class="container" ng-controller="report.custom.ctrl">
        <tree-view ng-model="jsonDataTree"></tree-view>
    </div>
</body>
           

指令代碼,toggle()方法是觸發每個菜單的事件。沒實作

m.directive('treeView', ["$window", 'T.window',
    function($window, window$){
        return {
            restrict : 'EA',
            require : '?ngModel',
            scope: {
                "ngModel": "="
            },
            template : `

            <div ng-repeat="sub in ngModel">
                <a ng-click="toggle()">
                    <span>{{sub.orgName}}</span>
                    <div style="margin-left:2em" ng-if="sub.children && sub.children.length">
                            <tree-view ng-model="sub.children"></tree-view>
                    </div>
                </a>
             </div>

            `,
            replace:true,
            link : function ($scope, element, attrs, ngModel) {
                console.error($scope)
            }
        };
    }
]);
           
tree架構疊代-angularjs

如果有多層會自動疊代下去,直到葉子節點。

繼續閱讀