The ngTable documentation lacks adequate information and sample codes, making it difficult to follow. Despite this, I was able to create the following code to dynamically fetch and display a table from the server. However, when I try to sort by clicking on the table header, the getData function (and consequently $http) is triggered again. As a result, after clicking, the column is not sorted, but the displayed data duplicates itself horizontally (for example, initially displaying columns [id, name], then becoming [id, name, id, name] after sorting).
<!DOCTYPE html>
<html>
<head lang="en">
<title><%= title %></title>
<meta charset="utf-8">
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="bower_components/ng-table/ng-table.min.js"></script>
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="bower_components/ng-table/ng-table.min.css" />
<script>
(function () {
'use strict';
let app = angular.module('myApp', ['ngTable']);
app.controller('demoCtrl', ['$http', 'NgTableParams', function ($http, NgTableParams) {
let ctrl = this;
ctrl.cols = [];
ctrl.rows = [];
ctrl.tableParams = new NgTableParams({}, {
getData: function (params) {
ctrl.xhr = $http({
method: 'GET',
url: '/ng-table-demo/test_data',
}).then(function (rsp) {
let cols = Object.keys(rsp.data[0]);
for(let i = 0; i < cols.length; i++) {
ctrl.cols.push({field: cols[i], title: cols[i], sortable: cols[i], show: true});
}
ctrl.rows = rsp.data;
return ctrl.rows;
}, function (rsp) {
console.log('http failed.');
});
return ctrl.xhr;
}});
}]);
})();
(function () {
"use strict";
angular.module("myApp").run(configureDefaults);
configureDefaults.$inject = ["ngTableDefaults"];
function configureDefaults(ngTableDefaults) {
ngTableDefaults.params.count = 5;
ngTableDefaults.settings.counts = [];
}})();
</script>
</head>
<body>
<div ng-app="myApp" ng-controller="demoCtrl as ctrl" class="container-fluid">
<h2>ng-table-demo</h2>
<table ng-table-dynamic="ctrl.tableParams with ctrl.cols" class="table table-condensed table-bordered table-striped">
<tr ng-repeat="row in $data">
<td ng-repeat="col in $columns">{{row[col.field]}}</td>
</tr>
</table>
</div>
</body>
</html>
I attempted to wrap the ctrl.xhr block with the following code snippet, which helped prevent duplication but did not resolve the issue with sorting.
if(ctrl.xhr === undefined) {
ctrl.xhr = $http...;
}
return ctrl.xhr;
What mistake(s) have I made?