我從一個 API 呼叫中得到一個嵌套的 JSON 物件,它看起來像這樣:
{
"name": “Main “Folder”,
"children": [
{
"name": “Child Folder 1”,
"children": []
},
{
"name": “Child Folder 2”,
"children": [
{
"name": “Sub Folder 1”,
"children": [
{
“name”: “Sub Sub Folder 1”,
“children”: []
}
]
},
{
"name": “Sub Folder 2” ,
"children": []
}
]
}
]
}
JSON物件可以嵌套多遠沒有限制,所以我不知道。我需要讓檔案夾的所有子級縮進到表中的父級下。我什至不確定該怎么做。我嘗試的第一件事是在我的 HTML 檔案中做這樣的事情,但我很快意識到它不會起作用。
檔案夾.html
<table>
<thead>
<tr><strong>{{ this.tableData.name }}</strong></tr>
</thead>
<tbody ng-repeat="b in this.tableData.children">
<tr>
<td>{{ b.name }}</td>
<td ng-repeat="c in b.children">{{ c.name }}</td>
</tr>
</tbody>
</table>
檔案夾.js
export default class FoldersController {
constructor($rootScope, $scope, $uibModal) {
this.tableData = {Example Data from top}
}
}
有沒有一種不太復雜的方法來做到這一點?謝謝!
uj5u.com熱心網友回復:
您應該使用包含表格的模板創建一個組件,然后您可以將組件嵌套在自身內部以遵循樹結構邏輯路徑:
你的根控制器應該包含你的表資料:
angular.module('app').controller('RootCtrl', ['$scope', function($scope) {
// assigning the data to $scope to make it available in the view
$scope.tableData = {Example Data from top};
}]);
你的樹組件可能是這樣的:
angular.module('app').component('treeComponent', {
controller: 'TreeCtrl',
bindings: {
tree: '<',
},
templateUrl: 'tree-view.html'
});
你的根模板應該加載組件的第一個實體:
<div>
<tree-component tree="tableData"></tree-component>
</div>
然后組件模板應在需要時處理遞回;樹視圖.html:
<table class="record-table">
<thead>
<tr>
<th>
<strong>{{ $ctrl.tableData.name }}</strong>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="node in $ctrl.tableData.children">
<td>{{node.name}}</td>
<td ng-if="node.children.length > 0">
<tree-component tree="node.children"></tree-component>
</td>
</tr>
</tbody>
</table>
然后使用基本 css 創建縮進變得容易:
.record-table .record-table {
padding-left: 20px
}
uj5u.com熱心網友回復:
我能夠在 js 檔案中使用遞回找出我自己的解決方案。我也實作了 mindthefrequency 的答案,它似乎作業得很好。我將其標記為最佳答案,因為它似乎是更清潔的解決方案,但我發布了我所擁有的內容,以防有人想要采用更面向 js 的方法。
首先,在 js 檔案中,使用遞回添加所有節點以及每個節點需要縮進到表資料變數中的距離。
檔案夾.js
export default class FoldersController {
constructor($rootScope, $scope, $uibModal) {
this.resp = {Example Data from top}
this.tableData = []
this.createTable(this.resp.children, 0, [
{
name: this.resp.name,
indent: '0px',
},
]);
}
createTable(children, count, data) {
count = 1;
// base case
if (!children || children.length === 0) {
return;
}
for (const child of children) {
const { name } = child;
const returnData = data;
returnData.push({
name: name,
indent: `${count * 25}px`,
});
this.tableData = returnData;
this.createTable(child.children, count, returnData);
}
}
}
然后,在 html 檔案中,使用 angularjs 正確縮進每個節點
檔案夾.html
<table>
<thead>
<tr><strong>Table Header</strong></tr>
</thead>
<tbody ng-repeat="b in vm.tableData">
<tr>
<td ng-style="{'padding-left': b.indent}">{{ b.name }}</td>
</tr>
</tbody>
</table>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/464221.html
