2

I'm working on a table directive that can accept a wide variety of data sources, normalizing the markup. I ran into an issue where my data object for rows can have children of it's own. Using this SO post, I constructed a new directive containing a recursive function to generate the HTML I desired, using this:

<nested-rows rows="rows" columns="columns"></nested-rows>

However, because of the dynamic nature of the row data, I'm not statically defining my td's.

Historically, I did this:

<td ng-repeat="column in columns">
  <cell-content renderer-id="column.rendererId" content="row[column.id]">
  </cell-content>
</td>

Where we're simply iterating the columns array, passing in the value of row.someColumn into a separate directive to generate different cell content (list, button, icon, etc..), where row.someColumn contains the necessary data for that particular column/column type.

The problem I'm having lies in this new directive. I don't have a variable row anymore, so calling row[column.id] is returning undefined. Here is my directive:

.directive('nestedRows', function($compile) {
    return {
        restrict: 'EA',
        replace: true,
        link: function(scope, element, attrs) {
            var html = "";
            var recursive = function(rows) {
                angular.forEach(rows, function(row, index) {
                    html +=
                        '<tr>' +
                            '<td ng-repeat="column in columns">' +
                            '<cell-content renderer-id="column.rendererId"' +
                                  'content="row[column.id]"></cell-content>' +
                            '</td>' +
                        '</tr>';
                    if(row.children) {
                        recursive(row.children);
                    }
                })
            }
            if(attrs && attrs.rows) {
                recursive(attrs.rows);
            }
            element.html(html);
            $compile(element.contents())(scope);
        }
    }
})

What I need to do is pass the proper data to my cellContent directive. How can I do this?

Community
  • 1
  • 1
Scott Silvi
  • 3,059
  • 5
  • 40
  • 63

1 Answers1

1

One way of doing this is to create a controller in your row directive and then 'require' it in your column directive.

In this context the controller is just a function which will be called when your parent directive is instantiated. Whatever is returned by the function will be passed to the directive requesting the controller in the 4th parameter of its 'compile' method.

See my ng-scroller directive for an example

Also see detailed description here

mfeingold
  • 7,094
  • 4
  • 37
  • 43