Description
I'm using AngularJS
I have a table that I want to show it as "Data Table" using DataTable jQuery plugin (http://datatables.net/docs/DataTables/1.9.4/DataTable.html).
The logic
- Create table table markup.
- Add
ng-repeatusing$scope.entitieson the row . - Run the plugin on the table.
The problem
In the first time that I run it, everything is OK.
The problem start when I need to change the $scope.entities (For example: user select another list)
In the snippets below I was created simpler scenario but the logic is same.
Steps
- Run the snippet (probably done automatic).
- Click on
destroybutton. It will destroy the plugin and return the table to original html. - Click on
Add row. It should add row to the table The problem is that all the rows were deleted instead of adding the row.
Note I saw some angular directives who integrating with the plugin (datatable). I can't using it. I need to understand why the view nodes are deleting.
angular.module('myApp', []).
controller('ctrl', function($scope, $timeout) {
$scope.test = 'test';
$scope.generateData = function() {
var temp = [];
for (var i = 0; i < 5; i++) {
temp.push({
d1: Math.floor(Math.random() * 10),
d2: Math.floor(Math.random() * 10),
d3: Math.floor(Math.random() * 10)
});
}
$scope.entities = temp;
$timeout(function(){
$scope.dt();
});
};
$scope.dt = function(){
$timeout(function() {
if (!$scope.dataTable) {
$scope.dataTable = $('table').dataTable();
}
});
}
$scope.destroy = function(){
if ($scope.dataTable) {
$scope.dataTable.fnDestroy();
}
}
$scope.addRow = function(){
$scope.entities.push({
d1: Math.floor(Math.random() * 10),
d2: Math.floor(Math.random() * 10),
d3: Math.floor(Math.random() * 10)
});
}
$scope.generateData();
});
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<link href="//cdn.datatables.net/1.9.4/css/jquery.dataTables.css" rel="stylesheet" />
<script src="//cdn.datatables.net/1.9.4/js/jquery.dataTables.min.js"></script>
<div data-ng-app="myApp" data-ng-controller="ctrl">
<table>
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="entity in entities">
<td data-ng-bind="entity.d1"></td>
<td data-ng-bind="entity.d2"></td>
<td data-ng-bind="entity.d3"></td>
</tr>
</tbody>
</table>
<button data-ng-click="destroy();">Destroy</button>
<button data-ng-click="addRow();">Add rows</button>
</div>