我设法通过实现动态改变容器高度的方法找到了解决方案。在控制器中,我首先使用 ng-style 初始化将在 JS 和模板中使用的变量:
//===================================================
// Initalize height that will be altered later based
// on tree expand/collapse events
//===================================================
var row_height = 30; // use this to set height everywhere
$scope.height = row_height;
$scope.height_px = row_height + 'px'; // used in template with ng-style
然后在初始化树视图网格选项时,可以参考 row_height。我们还在选项中添加了基于rowExpanded和rowCollapsed事件增加或减少高度的逻辑:
$scope.gridOptions = {
rowHeight: row_height,
enableSorting: true,
enableFiltering: false,
//.....continue other options.....
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
// Add container height for row expanded
$scope.gridApi.treeBase.on.rowExpanded(null, function(row) {
addHeight(row.treeNode.children.length);
});
// Deduct container height for row collapsed after considering
// all child node expanded state
$scope.gridApi.treeBase.on.rowCollapsed(null, function(row) {
// get number of children that are already expanded
var count = row.treeNode.children.length;
for(var i=0; i < row.treeNode.children.length; i++) {
count += getChildCount( row.treeNode.children[i]);
}
deductHeight(count);
});
}
}
然后我们将addHeight()、deductHeight() 和getChildCount() 工作所需的方法添加到控制器:
// Method to add height of container dynamically based on number of rows
var addHeight = function (num_rows) {
$scope.height += num_rows * row_height;
$scope.height_px = $scope.height + 'px';
};
// Method to deduct height of container dynamically based on number of rows
var deductHeight = function (num_rows) {
$scope.height -= num_rows * row_height;
if($scope.height <= 0) {
$scope.height = row_height;
}
$scope.height_px = $scope.height + 'px';
};
// Method to get count of expanded child rows for a given node (used recursively)
var getChildCount = function (node) {
var count = 0;
if(node.state == 'expanded') {
// change the state to collapsed for all child nodes
node.state = 'collapsed';
count += node.children.length;
for(var i=0; i < node.children.length; i++) {
count += getChildCount(node.children[i]);
}
return count;
} else {
return 0;
}
};
请注意,当我们折叠一个节点时,我们会递归地获取节点计数。我们还将子节点的状态更改为折叠状态,以便下次正确计算高度。
最后,在模板中,我们需要引用 $scope.height_px,它给出了容器的动态高度。我们通过如下设置ng-style="{ 'height': height_px }" 来做到这一点:
<div id="gridTree-1" ui-grid="gridOptions" class="grid" ui-grid-tree-view ui-grid-auto-resize ng-style="{ 'height': height_px }"></div>
在此之后我遇到的一个问题是鼠标滚动在放置在网格顶部时停止工作。这个问题显然有一个建议的解决方案here。但是,实际问题与ui-grid.js 中的滚动功能禁用有关。在版本 3.1.1 中,第 2721 行读取为event.preventDefault();。我必须注释掉这条线才能让滚动再次正常工作。