I am a beginner in AngularJS and I am attempting to create a tree data structure using filters in AngularJS.
Below is the HTML code snippet:
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<table class="table table-condensed">
<thead>
<tr>
<th ng-repeat="x in tableHeaders">
<label>[[ x.name ]]</label>
</th>
<th class="text-center"><label>Options</label></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in items | childrenFilter" ng-if="!noRecord">
<td>[[ x.name ]]</td>
<td>[[ x.code ]]</td>
<td class="text-center">
<a href="#/update/[[ x.id ]]"><span class="glyphicon glyphicon-pencil" data-toggle="tooltip" title="Update"></span></a>
<span class="glyphicon glyphicon-remove" data-toggle="tooltip" title="Delete"></span>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
And here is the JavaScript code section:
app = angular.module('myApp', []);
app.config(function($interpolateProvider, $httpProvider) {
// Change template tags
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
});
app.filter('childrenFilter', function(){
return function (items){
nodeKey = 'children';
for (var i = 0; i < items.length; i++) {
if(nodeKey in items[i]){
x = items[i];
while(nodeKey in x){
x = x[nodeKey];
for(y=0;y<x.length;y++){
x = x[y];
}
}
}
}
return items;
}
});
app.controller('myCtrl', function($scope){
$scope.items = [
{
"name": "Tankers",
"code": "TANK",
"id": 1,
"children": [
{
"name": "Oiler",
"code": "OIL",
"id": 2
},
{
"name": "Chemical",
"code": "CHEM",
"id": 3,
"children": [
{
"name": "Production",
"code": "PROD",
"id": 6
}
]
}
]
},
{
"name": "Bulker",
"code": "BULK",
"id": 4,
"children": [
{
"name": "Logger",
"code": "LOG",
"id": 5
}
]
},
{
"name": "Sterilized",
"code": "STER",
"id": 21
}
];
$scope.tableHeaders = [
{'name': 'Name.'},
{'name': 'Code'},
{'name': 'Updated By'},
{'name': 'Date Updated'},
];
});
To be frank, I'm currently facing some challenges with this task and my goal is to achieve something similar to the image provided below, where all the children of a specific object are displayed indented and can be toggled: