问题描述
-
datatables
框架和Angularjs
的ng-repeat
指令一起使用的时候会出现数据无法在表格中展现的错误,点击下表格的 head ,数据就会消失。在 datatables 的官网也有人问过这个问题 is-there-a-way-to-use-ng-repeat-and-datatables。错误如图:
ng-repeat
需要的数据需要从ajax
请求异步获取,导致表格比数据先渲染出来,然后无法把表格中的数据导出到excel
$scope.$on
调用多次的问题
解决办法:
使用
angular-datatables
框架解决使用
angular
的directive
和$timeout
方式解决。$scope.$on
调用多次需要使用destroy
的方式解决
总体代码如下:
表格部分的代码
<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 代码:
<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>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。