datatables
框架和 Angularjs
的 ng-repeat
指令一塊兒使用的時候會出現數據沒法在表格中展示的錯誤,點擊下表格的 head ,數據就會消失。在 datatables 的官網也有人問過這個問題 is-there-a-way-to-use-ng-repeat-and-datatables。javascript
錯誤如圖:
ng-repeat
須要的數據須要從 ajax
請求異步獲取,致使表格比數據先渲染出來,而後沒法把表格中的數據導出到 excel
java
$scope.$on
調用屢次的問題ajax
使用 angular-datatables
框架解決json
使用 angular
的 directive
和 $timeout
方式解決。app
$scope.$on
調用屢次須要使用 destroy
的方式解決框架
整體代碼以下:異步
表格部分的代碼url
<table id="main" class="table table-bordered" datatable="ng"> <thead> <tr> <th>a</th> <th>b</th> <th>c</th> <th>d</th> <th>e</th> </tr> </thead> <tbody> <tr ng-repeat="item in items track by $index" ng-model="items" on-finish-render="ngRepeatFinished"> <td>{{item.a}}</td> <td>{{item.b}}</td> <td>{{item.c}}</td> <td>{{item.d}}</td> <td>{{item.e}}</td> </tr> </tbody> </table>
JS 代碼:spa
<script type="text/javascript"> var myapp = angular.module("main", ['datatables']); myapp.directive('onFinishRender', function ($timeout) { return { restrict: 'A', link: function (scope, element, attr) { if (scope.$last) { $timeout(function () { scope.$emit(attr.onFinishRender); }); } } } }); myapp.controller("mainCtrl", ['$scope', '$http', function ($scope, $http) { $scope.trv = {orders: ""}; $scope.errMsg = ""; $scope.isDisabled = false; $scope.items = {}; //調用以後銷燬,避免調用兩次 var destroyFoo = $scope.$on('ngRepeatFinished', function() { $("table").tableExport(); }); $scope.$on('ngRepeatFinished', function() { destroyFoo(); console.log("test"); }); $scope.test= function () { if ($scope.trv.orders== '') { alert("數據不能爲空!"); return; } $scope.isDisabled = true; var bArray = $('#orders').val().replace(/\s+/g, ","); var cArray = bArray.split(","); var dUnique = $.unique(cArray); console.log(dUnique); var estr = $.map(dUnique, function (val, index) { var str = val; return str; }).join(","); console.log(estr); var data = {items: estr}; var url = "/a/b.json"; console.log(data); $http({ method: "POST", dataType: "json", contentType: 'application/json', url: url, data: data, }).success(function (data) { if (data.success) { $scope.errMsg = ""; $scope.items = $.parseJSON('[' + formatData(data.data) + ']'); alert("查詢完成"); } else { $scope.errMsg = data.message; console.log("有問題的數據:" + data.data); $scope.items = data.data; $scope.isDisabled = false; } }).error(function (data) { alert(data); $scope.isDisabled = false; }); }; function formatData(data) { var lastData = []; var pObj = {'a': "", 'b': "", 'c': "", 'd': "", 'e': ""}; Object.keys(data).forEach(function (k) { data[k].forEach(function (element) { var vm = JSON.stringify(element); pObj.a = k; pObj.b = element.b; pObj.c = element.c; pObj.d = element.d; pObj.e = element.e; lastData.push(JSON.stringify(pObj)); }); }); return lastData; } }]); </script>