AngularJS table directive

AngularJS is a very promising and fast-paced javascript framework. I tried many frameworks and settled on this because it literally makes it possible to revitalize the layout. I really like the implementation of directives, which makes it possible to prepare some elements for frequent use. On the Internet there are a lot of examples and ready-made solutions, 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 capabilities: loading data with an ajax, breaking a large amount of data into pages, filtering data and sorting.
I wanted to solve these problems quickly and by writing a minimal amount of code.
Here's what happened:
Repository on GitHub
{[user.name]} {[user.age]}

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 you can see from the html code, the programmer controls the filling of the lines of the table and the template for displaying each cell in it, which is the distinguishing feature that distinguishes this solution from the others I have examined, for example, ng-grid .

The table heading and pagination are automatically generated and added to the table. The entire relationship between the directive and the data loading code is assigned to a parameter tableParams, the tracking of which helps to know when to update the data (download from the server or re-sort the array).

As a result, we have a small directive that makes life a little better. I think that there are few solutions of this kind on the Internet because of one small bug in AngularJS itself. In truth, if it weren’t, then everything would be solved simply with the help of a very cool and useful tag ng-transclude. But until it has been fixed, I hope my solution will be useful to you.

Also popular now: