'Passing HTML to a custom directive
I'm new at angular and I'm trying to do something at work to easily create tables with functionality such as CRUD functions.
For example:
I have the following declaration:
<custom-table datasource="persons" headers="headers">
<custom-column header="header" display-member=""/>
<custom-column header="header" display-member=""/>
</custom-table>
Which my custom-table is a directive which returns an table element. The problem is, I have to read ALL columns in order to build the header and body of a table, but I can't figure out how I can read the columns that I passed as content of directive... (I'm trying to use less jQuery as possible)
The only thing that I could achieve it was read each column separated, but doing this, I will not be able to build the table correctly. The scenario that I'm imagined is, read all column declaration, build the table header, and put an ng-repeat for body.
Solution 1:[1]
In order to get the content of you directive ( your columns definitions ) you can do couple of things. But this is some advanced usage of angular and not sure if you should do what you want this way:
1 - Use the transclude function to compile the innerHtml. Your directive link function can receive the transcludeFn as the 5th argument, this function allows you to compile whatever is inside your directive and them use it as you want.
2 - Implement the compile function for you directive. The compile function will receive the html and you can query it to extract the innerHtml.
If I were solving the same problem, instead of looking for the directive content, I would rather make the table columns directives as well.
You might want to look at how angular-Ui/bootstrap project implemented the tabs component regarding its relation with the child tab and how they talk each other.
Solution 2:[2]
I think there's merit in creating directives for this purpose, but how about just building the table on the fly. Here's a codepen
<table>
<thead>
<tr>
<th ng-repeat="value in table.data.headers">{{value}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in table.data.body">
<td ng-repeat="property in item">{{property}}</td>
</tr>
</tbody>
</table>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thiago Felix |
| Solution 2 |
