我喜欢Tony的方法。它很有效,但我决定采用不同的方式实现。以下是我的评论:
1)我进行了一些测试,当使用ng-style时,Angular会评估ng-style内容,也就是说会多次调用getTableHeight()函数。我在getTableHeight()函数中设置了断点来分析这个问题。
顺便说一下,ui-if已被移除。现在你可以使用ng-if内置指令。
2)我更喜欢写一个类似这样的服务:
angular.module('angularStart.services').factory('uiGridService', function ($http, $rootScope) {
var factory = {};
factory.getGridHeight = function(gridOptions) {
var length = gridOptions.data.length;
var rowHeight = 30;
var headerHeight = 40;
var filterHeight = 40;
return length * rowHeight + headerHeight + filterHeight + "px";
}
factory.removeUnit = function(value, unit) {
return value.replace(unit, '');
}
return factory;
然后在控制器中编写以下内容:
angular.module('app',['ui.grid']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {
...
$scope.gridHeight = uiGridService.getGridHeight($scope.gridData);
在HTML文件中:
<div id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize style="height: {{gridHeight}}"></div>
当Angular应用样式时,它只需要查看$scope.gridHeight变量,而不必评估完整的函数。
3)如果您想动态计算可扩展网格的高度,则更加复杂。在这种情况下,您可以设置expandableRowHeight属性。这将为每个子网格固定保留高度。
$scope.gridData = {
enableSorting: true,
multiSelect: false,
enableRowSelection: true,
showFooter: false,
enableFiltering: true,
enableSelectAll: false,
enableRowHeaderSelection: false,
enableGridMenu: true,
noUnselect: true,
expandableRowTemplate: 'subGrid.html',
expandableRowHeight: 380,
onRegisterApi: function(gridApi) {
gridApi.expandable.on.rowExpandedStateChanged($scope, function(row){
var height = parseInt(uiGridService.removeUnit($scope.jdeNewUserConflictsGridHeight,'px'));
var changedRowHeight = parseInt(uiGridService.getGridHeight(row.entity.subGridNewUserConflictsGrid, true));
if (row.isExpanded)
{
height += changedRowHeight;
}
else
{
height -= changedRowHeight;
}
$scope.jdeNewUserConflictsGridHeight = height + 'px';
});
},
columnDefs : [
{ field: 'GridField1', name: 'GridField1', enableFiltering: true }
]
}