5

(Note that you don't need to know about datatables for this one..)

I'm creating a directive to handle DataTables. What I'd like to do is have an actions column with two icons - edit and delete. Those icons should response to an ng-click.

Datatables allow you do this by providing a callback for a given column defintion (mRender). This callback returns an html string for that cell value, which is inserted into the DOM instead of the actual cell value.

Checkout this plunker. The two important functions are highlighted:

  • renderActionIcon - my implementation of the callback mentioned above. It generates the HTML string that I'd like in the cell.
  • registerNewHtmlWithAngular - function where I ostensibly let angular know about the ng-clicks that I need to register for that column.

What should go in registerNewHtmlWithAngular?

If $compile the html, angular adds the appropriate click event listeners and gives me back an element, but since the Datatables function expects HTML, those registered elements will not be added to the DOM.

Any ideas? Thanks folks!

Roy Truelove
  • 22,016
  • 18
  • 111
  • 153

2 Answers2

10

After a day of keyboard banging:

There does not seem to be a way to $compile into html and have it be usable in the DOM. It has to be an element that's inserted into the DOM, so that event listeners are not lost.

The way I solved the problem in this particular scenario is to just insert the HTML, and run $compile on the new HTML later.

Datatables makes this easy with the fnCreatedRow callback, which, after a row is rendered, passes back a row's Element and lets you do whatever you want with it. In this case I ran $compile over the row and returned it back to Datatables. See the rowCompiler function in the updated plunker.

Roy Truelove
  • 22,016
  • 18
  • 111
  • 153
  • 1
    huge thanks for the hint on compiling row within `fnCreatedRow`!! I'm working on a directive for DataTables as well, actually I've started from someone else's attempt. It might be worth sharing the work... – superjos Mar 06 '13 at 14:25
  • Unf it's for work, so I'd expect a slap on the wrist if I posted it. One thing I learned the hard way though - I tried to made a generic datatables directive to handle all of my tables. In the long term, though, I made a 'datatablesHelper' service which has all of the generic code, and each table has it's own directive with that service injected. – Roy Truelove Mar 06 '13 at 15:49
  • I understand. Fair enough! :) – superjos Mar 06 '13 at 15:50
0

Because datatables uses innerHTML = mRender(...) to insert an html (so it anyway will convert anything to string and you will lose the results of $compile function. I guess there is no way to do it with mRender without hacks - for instance it is possible to slightly change datatables so it will use $.append instead of innerHTML. But this is not a good practice so in our project we use usual jquery bindings instead of ng-click.

Ivan Buryak
  • 633
  • 5
  • 13