我是AngularJS的新手,我希望使用AngularJS的过滤器来创建树数据。
以下是我的HTML代码:
<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">
<!-- <ul>
<li ng-repeat="friend in friends | removeBlank ">
[[ friend.name]]
</li>
</ul> -->
<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>
这是我的JS:
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'},
];
});
要诚实我有点卡住了,我想要达到的目的与下图相似。其中某个对象的所有子项都附加缩进并且可以切换
答案 0 :(得分:-1)
你应该在StackOverflow上搜索一下我的内容。我发现了你想要实现的另一个问题: the issue和plnkr。 我不认为过滤器可以用于你的例子。
在JS中定义对象时,您不需要为属性添加引号:name
,code
,id
,children
等。
var data = [{
name: "Tankers",
code: "TANK",
id: 1,
children: [
// ...
],
// ...
}];
此外,在AngularJS中,您不仅可以在对象上迭代ng-repeat
,还可以在数组上迭代:
$scope.tableHeader = ["Name", "Code", "Updated By", "Date Updated", "Options"];
然后:
<th ng-repeat="header in tableHeader">{{header}}</th>
这是fiddle,其中包含对代码的一些更正。
一般来说,AngularJS有很多模块可用于各种功能。 例如,我认为UI Grid可以帮助您实现所需。