【发布时间】:2026-02-01 20:35:01
【问题描述】:
我有这样的分层数据:
[
{
"children":[
{
"children":[...],
[...]
},
{
"children":[...],
[...]
},
],
[...]
}
]
我想通过展平这些数据来构建树状网格。我正在使用以下指令:
app.directive('tree', function (hierarchyService, logger, $timeout) {
return {
scope: {
data: '='
},
restrict: 'E',
replace: true,
template: '<div>' +
'<table class="table table-striped table-hover">' +
' <thead>' +
' <tr>' +
' <th class="col-md-6">Account name</th>' +
' </tr>' +
' </thead>' +
' <tbody><tr collection data="data" /></tbody>' +
' </table>' +
'</div>'
};
});
app.directive('collection', function() {
return {
restrict: "A",
replace: true,
scope: {
data: '=',
depth: '@'
},
template: '<member ng-repeat="member in data" member="member" depth="{{depth}}" />',
link: function (scope, element, attrs) {
scope.depth = parseInt(scope.depth || 0);
}
}
});
app.directive('member', function($compile) {
return {
restrict: "E",
replace: true,
scope: {
depth: '@',
member: '='
},
template: '<tr ng-class="{selected: member.selected}">' +
'<td>' +
' <span ng-show="depth > 0" style="width: {{depth * 16}}px; display: inline-block;"></span> {{member.name}}' +
'</td>' +
'</tr>',
link: function (scope, element, attrs) {
scope.depth = parseInt(scope.depth || 0);
if (angular.isArray(scope.member.children) && scope.member.children.length > 0) {
var el = angular.element('<tr collection data="member.children" depth="{{newDepth}}" />');
scope.depth = parseInt(scope.depth || 0);
scope.newDepth = scope.depth + 1;
$compile(el)(scope);
// Flatten hierarchy, by appending el to parent
element.parent().append(el);
}
}
}
});
问题是,在从link 方法添加的集合中,来自父作用域的depth 被附加到newDepth。因此,级别 3 节点的 depth 具有值 depth="3 2 1 "。
如何禁用depth的继承?
我还注意到,当我在 collection 和 member 指令中将 replace 更改为 false 时,深度按预期工作,但 HTML 无效。
【问题讨论】:
-
你能为你的案子提供一个 plunker 或 fiddle 吗?
-
@SpartakLalaj 你在这里:plnkr.co/edit/CE2z5WeU41H4qJQQ73B7?p=preview
-
我删除了 depth 属性并在集合中用等号声明它,似乎数字是正确的。试试看这是否是正确的结果!
-
修改后的plunker是这样的:plnkr.co/edit/w794aydNu8rkeYj8dEWl?p=preview
标签: javascript angularjs angularjs-directive hierarchy