AngularJS dynamic table with multiple headers based on hierarchical collections

1.7k Views Asked by At

I'm trying to create a table with two rows for header, based on a hierarchical collection. I've found that ng-repeat can't do that, and I'm trying to make the job with a directive and Angular.forEach.

Here the jsfiddle : http://jsfiddle.net/echterpat/RxR2M/9/

But my problem is that when I made the first display of table, collections were empty (they were filled by REST call afterward), so link method was not able to build all the table. And then when REST updated collections, link method was not called anymore...

Any idea to call directive after REST answer, and to fill my table with collected data ?

Directive with angular.forEach :

myApp.directive('myTable', ['$compile', function (compile) {
var linker = function (scope, element, attrs) {
    var html = '<table BORDER="1"><thead>';
    html += '<tr><th><button type="submit" class="btn btn-info">Back</button></th>';
    angular.forEach(scope.myFirstCol, function (item, index) {
        html += '<th colspan="{{item.mySecondCol.length}}" id="item_{{item.id}}">    {{item.name}}</th>';
    });
    html += '</tr><tr><th><input type="checkbox" ng-model="selectAll"/></th>';
    angular.forEach(scope.myFirstCol, function (item2, index) {
        angular.forEach(item2.mySecondCol, function (item3, index) {
            html += '<th id="headerStep_{{item3.id}}">{{item3.name}}</th>';

        });
    });
    html += '</tr></thead>';
    html += '</table>';
    element.replaceWith(html);
    compile(element.contents())(scope);
    };

    return {
    restrict: 'E',
    rep1ace: true,
    link: linker,
    scope: {
        myFirstCol: '=myFirstCol'
    }
};

}]);
1

There are 1 best solutions below

0
On

If you dont want to use a directive, you can go for nested tables:

<table BORDER="1">
    <thead>
        <tr>
            <th>
                <button type="submit" class="btn btn-info">Back</button>
            </th>
            <th ng-repeat="item in myFirstCol">{{item.name}}</th>                
        </tr>
        <tr>
            <th>
                <input type="checkbox" ng-model="selectAll" />
            </th>
            <th ng-repeat="item in myFirstCol">
                <table BORDER="1">
                    <tr>
                        <th ng-repeat="item2 in item.mySecondCol">
                            {{item2.name}}
                        </th>
                    </tr>
                </table>
            </th>                
        </tr>
    </thead>
</table>