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

如果有多层会自动迭代下去,直到叶子节点。