📜 ⬆️ ⬇️

Directive for working with tables on AngularJS

AngularJS is a very promising and fast-growing javascript framework. I tried many frameworks and stopped there because it literally makes it possible to revive the layout. I really like the implementation of the directives, which make it possible to prepare some elements for frequent use. There are a lot of examples and ready-made solutions on the Internet, but I did not find one solution, this was the reason for writing this article and a small library.

I often come across data, namely the presentation of data in a table. Each such interface should have several possibilities: loading data with an Ajax, splitting a large amount of data into pages, filtering data and sorting.
I wanted to solve these problems quickly and by writing the minimum amount of code.
Here's what I got:
GitHub Repository
<table ng-table="tableParams" show-filter="true" class="table"> <tr ng-repeat="user in users"> <td title="Name" filter="{ 'name': 'text' }" sortable="name"> {[user.name]} </td> <td title="Age" filter="{ 'action': 'button' }" sortable="age"> {[user.age]} </td> </tr> </table> 

Javascript:
 var Api = $resource('/data'); $scope.tableParams = new ngTableParams({ page: 1, // show first page total: 0, // length of data count: 10, // count per page sorting: { name: 'asc' // initial sorting } }); $scope.$watch('tableParams', function(params) { $scope.loading = true; // ajax request to api Api.get(params.url(), function(data) { $scope.loading = false; // set new data $scope.users = data.result; // update table params $scope.tableParams.total = data.total; }); }, true); 

Demo

As can be seen from the html code, the programmer himself controls the filling of the lines of the table and the display pattern of each cell in it, which is a distinctive feature that distinguishes this solution from the others I have reviewed, for example, ng-grid .

The table cap and page breakdown are automatically generated and added to the table. The entire relationship between the directive and the data load code is entrusted to the tableParams parameter, tracking of which helps to know when data needs to be updated (download from the server or re-sort the array).
')
As a result, we have a little directive that makes life a little better. I think that there are few solutions of this kind on the Internet due to one small bug in AngularJS itself . In truth, if it were not there, then everything would be solved simply with the help of a very cool and useful ng-transclude . But until he was corrected, I hope my decision will be useful to you.

Source: https://habr.com/ru/post/181778/


All Articles