使用AngularJS和特定的数据结构创建简单的可扩展/可折叠树视图可以通过以下步骤实现:
以下是一个示例代码,展示如何使用AngularJS和特定的数据结构创建简单的可扩展/可折叠树视图:
HTML文件:
<!DOCTYPE html>
<html lang="en" ng-app="treeApp">
<head>
<meta charset="UTF-8">
<title>AngularJS Tree View</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div ng-controller="treeController">
<tree-node ng-repeat="node in treeData" node="node"></tree-node>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular-sanitize.min.js"></script>
<script src="app.js"></script>
</body>
</html>
JavaScript文件(app.js):
angular.module('treeApp', ['ngAnimate', 'ngSanitize'])
.controller('treeController', function($scope) {
$scope.treeData = [
{
id: 1,
name: 'Node 1',
children: [
{
id: 2,
name: 'Node 1.1',
children: []
},
{
id: 3,
name: 'Node 1.2',
children: [
{
id: 4,
name: 'Node 1.2.1',
children: []
}
]
}
]
},
{
id: 5,
name: 'Node 2',
children: []
}
];
})
.directive('treeNode', function() {
return {
restrict: 'E',
scope: {
node: '='
},
template: `
<div class="node">
<span ng-click="toggleNode()">{{ node.name }}</span>
<div ng-show="node.children.length" ng-hide="node.collapsed">
<tree-node ng-repeat="child in node.children" node="child"></tree-node>
</div>
</div>
`,
link: function(scope) {
scope.toggleNode = function() {
scope.node.collapsed = !scope.node.collapsed;
};
}
};
});
CSS文件(styles.css):
.node {
margin-left: 20px;
}
.node span {
cursor: pointer;
}
.node div {
margin-left: 20px;
}
这个示例代码创建了一个简单的可扩展/可折叠树视图,每个节点都可以展开或折叠其子节点。你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云