ahsan ayub
ahsan ayub

Reputation: 307

JQuery Datatable in Angular Js Ng-Click not Working?

I have a DataTable and I am loading it using Angular Js, I have Created a directive and wrapped my DataTable in this directive, A common approach of wraping JQuery Plugin in Directive so that it can live in Angular Digest Cycle. But the ng-click that is on button and coming from render Function of column in datatable is not clickable (Not Working, Angular did not compiled it). Is there any way to make it Clickable. I know the approach in which we use {{}} with ng-repeatto populate data in datatable. I'm looking a directive way, so you can tell me what is stoping ng-click from working or how to make my directive right! Please stick with directive approach. Code is following.

App.directive('jqtable', function () {
return {
    restrict: 'E, A, C',
    link: function (scope, element, attrs, controller) {
        var dataTable = element.dataTable(scope.options);
         scope.$watch('options.data',  handleModelUpdates, true);
            function handleModelUpdates(newData) {
            var data = newData || null;
            if (data) {
                dataTable.fnClearTable();
                dataTable.fnAddData(data);
            }
        }
    },
    scope: {
        options: "="
    }
};

});

And here is my Controller:-

$scope.options = {
   aoColumnDefs: [{
        "bSortable": true,
        "aTargets": [ 1],
        "render": function ( data, type, full, meta ) {
            if(meta.col==1){
                return data+" <a class='btn btn-sm btn-default' ng-click='showalert()' >Click me </a>"
            }
        }
    }],
    bJQueryUI: true,
    bDestroy: true,
    data:$scope.data                        
};
$scope.showalert=()=>
{
    alert("Angular Compiled the Html");
}

Upvotes: 1

Views: 1674

Answers (1)

davidkonrad
davidkonrad

Reputation: 85578

Angular does not know you have injected elements to the DOM. You must $compile each row. You can do that in rowCallback. Since DataTables may inject new rows when the table is filtered, sorted or upon page change, you can add a compiled flag to prevent rows from being $compiled multiple times :

$scope.options = {
  rowCallback: function(row) {  
    if (!row.compiled) {
      $compile(angular.element(row))($scope);
      row.compiled = true;  
    }  
  }
  ...
}

see http://next.plnkr.co/edit/KxwqSVXIogtXYx4I

Upvotes: 2

Related Questions