本文转自:http://pointblankdevelopment.com.au/blog/angularjs-fixed-header-scrollable-table-directive

This post contains a custom AngularJS directive you can use to give your html table a fixed header and footer with a scrollable body, we developed it for a law firm marketing website recently, it uses a pure CSS approach and doesn't touch any of the html tags, leaving the html table completely intact and happily semantic :)

Creating a fixed header scrollable table using purely CSS turns out to be a surprisingly tricky thing to do, in an ideal world I thought it would just be a matter of setting the height of the table body and "overflow:hidden", but there turns out to be a bit more to it than that, especially if you have a table that contains dynamic content because the width of each column in the thead and tbody need to be set in order for it to continue looking like a table and not just a big mess.

In a nutshell the CSS changes that need to happen are:

  • Set the width of each column in the thead and tbody, making sure they match up so the columns aren't wonky
  • Set the thead and tbody to "display:block;"
  • Set the tbody height and "overflow:auto;" to add the scrollbar
  • When there's a scrollbar (when the tbody content overflows it's height), reduce the width of the final column in the tbody by the width of the scrollbar

Here's the solution I came up with:

The fixedHeader AngularJS directive

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
 * AngularJS fixed header scrollable table directive
 * @author Jason Watmore <jason@pointblankdevelopment.com.au> (http://jasonwatmore.com)
 * @version 1.2.0
 */
(function () {
    angular
        .module('anguFixedHeaderTable', [])
        .directive('fixedHeader', fixedHeader);
 
    fixedHeader.$inject = ['$timeout'];
 
    function fixedHeader($timeout) {
        return {
            restrict: 'A',
            link: link
        };
 
        function link($scope, $elem, $attrs, $ctrl) {
            var elem = $elem[0];
 
            // wait for data to load and then transform the table
            $scope.$watch(tableDataLoaded, function(isTableDataLoaded) {
                if (isTableDataLoaded) {
                    transformTable();
                }
            });
 
            function tableDataLoaded() {
                // first cell in the tbody exists when data is loaded but doesn't have a width
                // until after the table is transformed
                var firstCell = elem.querySelector('tbody tr:first-child td:first-child');
                return firstCell && !firstCell.style.width;
            }
 
            function transformTable() {
                // reset display styles so column widths are correct when measured below
                angular.element(elem.querySelectorAll('thead, tbody, tfoot')).css('display', '');
 
                // wrap in $timeout to give table a chance to finish rendering
                $timeout(function () {
                    // set widths of columns
                    angular.forEach(elem.querySelectorAll('tr:first-child th'), function (thElem, i) {
 
                        var tdElems = elem.querySelector('tbody tr:first-child td:nth-child(' + (i + 1) + ')');
                        var tfElems = elem.querySelector('tfoot tr:first-child td:nth-child(' + (i + 1) + ')');
 
                        var columnWidth = tdElems ? tdElems.offsetWidth : thElem.offsetWidth;
                        if (tdElems) {
                            tdElems.style.width = columnWidth + 'px';
                        }
                        if (thElem) {
                            thElem.style.width = columnWidth + 'px';
                        }
                        if (tfElems) {
                            tfElems.style.width = columnWidth + 'px';
                        }
                    });
 
                    // set css styles on thead and tbody
                    angular.element(elem.querySelectorAll('thead, tfoot')).css('display', 'block');
 
                    angular.element(elem.querySelectorAll('tbody')).css({
                        'display': 'block',
                        'height': $attrs.tableHeight || 'inherit',
                        'overflow': 'auto'
                    });
 
                    // reduce width of last column by width of scrollbar
                    var tbody = elem.querySelector('tbody');
                    var scrollBarWidth = tbody.offsetWidth - tbody.clientWidth;
                    if (scrollBarWidth > 0) {
                        // for some reason trimming the width by 2px lines everything up better
                        scrollBarWidth -= 2;
                        var lastColumn = elem.querySelector('tbody tr:first-child td:last-child');
                        lastColumn.style.width = (lastColumn.offsetWidth - scrollBarWidth) + 'px';
                    }
                });
            }
        }
    }
})();

Sample HTML that uses the fixed-header directive

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<table class="table table-bordered" fixed-header>
    <thead>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
            <th>Header 3</th>
            <th>Header 4</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="item in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]">
            <td>Row {{item}} Col 1</td>
            <td>Row {{item}} Col 2</td>
            <td>Row {{item}} Col 3</td>
            <td>Row {{item}} Col 4</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>Footer 1</td>
            <td>Footer 2</td>
            <td>Footer 3</td>
            <td>Footer 4</td>
        </tr>
    </tfoot>
</table>

The default height of the table body is 400px, to change this add a table-height attribute to the table element eg: table-height="500px".

UPDATE 08/10/2014: Added support for fixed footer (tfoot) element.

[转]AngularJS fixed header scrollable table directive的更多相关文章

  1. AngularJS:何时应该使用Directive、Controller、Service?

    AngularJS:何时应该使用Directive.Controller.Service? (这篇文章你们一定要看,尤其初学的人,好吗亲?) 大漠穷秋 译 AngularJS是一款非常强大的前端MVC ...

  2. Part 10 AngularJS sort rows by table header

    Here is what we want to do 1. The data should be sorted when the table column header is clicked 2. T ...

  3. AngularJS Best Practices: ng-include vs directive

    For building an HTML template with reusable widgets like header, sidebar, footer, etc. Basically the ...

  4. AngularJS:何时应该使用Directive、Controller、Service?【新手必看】

    (这篇文章你们一定要看,尤其初学的人,好吗亲?) 大漠穷秋 译 AngularJS是一款非常强大的前端MVC框架.同时,它也引入了相当多的概念,这些概念我们可能不是太熟悉.(译者注:老外真谦虚,我大天 ...

  5. AngularJs学习——何时应该使用Directive、Controller、Service?

    翻译:大漠穷秋 原文链接:http://kirkbushell.me/when-to-use-directives-controllers-or-services-in-angular/ 一.简述 A ...

  6. [转]AngularJS:何时应该使用Directive、Controller、Service?

    AngularJS是一款非常强大的前端MVC框架.同时,它也引入了相当多的概念,这些概念我们可能不是太熟悉.(译者注:老外真谦虚,我大天朝的码农对这些概念那是相当熟悉啊!)这些概念有: Directi ...

  7. [AngularJS] Build Your Own ng-controller Directive

    /** * Created by Answer1215 on 12/21/2014. */ angular.module('app', []) .controller('FirstCtrl' , fu ...

  8. angularJS+requireJS实现controller及directive的按需加载

    最近因为项目的比较大,需要加载的js文件较多,为了提高首屏页面的加载速度,需要对js文件进行按需加载,然后网上参考了一些资料,自己也深入研究一番之后,实现了按需加载控制器js文件及指令js文件的效果: ...

  9. AngularJS之Directive,scope,$parse

    AngularJS内幕详解之 Directive AngularJS内幕详解之 Scope AngularJS的指令(Directive) compile和link的区别及使用示例 浅谈Angular ...

随机推荐

  1. Page Scroll Effects - 简单的页面滚动效果

    Codyhouse 收集了一组页面滚动效果,就是目前大家很常见的用户在浏览网页的时候.一些效果虽然极端,但如果你的目标是创建一个身临其境的用户体验,他们是非常有用的.所有的动画都使用 Velocity ...

  2. 【javascript激增的思考02】模块化与MVC

    前言 之前我们遇到了这么一个项目,也就是我们昨天提到的,有很多的小窗口的,昨天说的太抽象了,今天我们再来理一理什么是小窗口(后面点说下),当时由于js有一点复杂,我自己也装B跟风用了一下传说中MVC! ...

  3. javascript 对象初探(二)--- 返回对象的函数

    除了使用new操作符调用构造函数以外,我们也可以抛开new操作符,只用一般函数来创建对象,这样就能执行某些预备工作,并已对象为返回值的函数.. function her(){ return { nam ...

  4. C4.5(决策树)

    C4.5是一系列用在机器学习和数据挖掘的分类问题中的算法.它的目标是监督学习:给定一个数据集,其中的每一个元组都能用一组属性值来描述,每一个元组属于一个互斥的类别中的某一类.C4.5的目标是通过学习, ...

  5. Revit如何模型导入到InfraWorks中

    Infraworks也就是以前的Autodesk Infrastructure Modeler(AIM)作为一款优秀的概念设计软件,能接收来自各种来源的数据,这篇介绍如何把revit中的建筑模型导入到 ...

  6. 开发Android系统内置应用小记

    Android系统内置应用可以使用更多的API.更高的权限,与开发普通应用最大的差别在于编译,内置应用编译需要用到Android.mk文件.下面是我在开发过程中的一些小记. 1.在AndroidMai ...

  7. 你真的了解UIApplication吗?

    一:首先查看一下关于UIApplication的定义 NS_CLASS_AVAILABLE_IOS(2_0) @interface UIApplication : UIResponder //获得单例 ...

  8. iOS关于CAShapeLayer与UIBezierPath的知识内容

    使用CAShapeLayer与UIBezierPath可以实现不在view的drawRect方法中就画出一些想要的图形 . 1:UIBezierPath: UIBezierPath是在 UIKit 中 ...

  9. xcode7无证书真机调试 Error: An App ID with identifier "*" is not avaliable. Please enter a different string.

    1. Error: An App ID with identifier "*" is not avaliable. Please enter a different string. ...

  10. 【原+转】用CMake代替makefile进行跨平台交叉编译

    在开始介绍如何使用CMake编译跨平台的静态库之前,先讲讲我在没有使用CMake之前所趟过的坑.因为很多开源的程序,比如png,都是自带编译脚本的.我们可以使用下列脚本来进行编译: ./configu ...