Sort angularjs tables easily
npm install angular-tablesortAngularJS Tablesort
===================
Allow tables to be sorted by clicking their headings.
Web site: http://mattiash.github.io/angular-tablesort
Background
----------
When you use jquery to build your web-pages, it is very easy to add sorting functionality to your tables - include tablesorter and annotate your column headings slightly to tell it what type of data your table contains.
The goal with this module is to make it just as easy to add sorting to AngularJS tables, but with proper use of angular features and not jQuery.
Click once on a heading to sort ascending, twice for descending. Use shift-click to sort on more than one column.
Additionally, these directives also make it easy to add a default row that is shown in empty tables to make
it explicit that the table is intentionally empty and not just broken.
Installation
------------
bower install angular-tablesort
or
npm install angular-tablesort
Usage
-----
Include the script in your markup
``html`
Include the module in your app
`js`
angular.module('myApp', ['tableSort']);
The following code generates a table that can be sorted by clicking on the table headings:
`html`
Id
Name
Price
Quantity
Date Ordered
#{{item.Id}}
{{item.Name}}
{{item.Price | currency}}
{{item.Quantity}}
{{item.OrderDate | date:"medium"}}
The ts-wrapper attribute must be set on element that surrounds both the headings and the ng-repeat statement.
The ts-criteria attribute tells tablesort which expression it should sort on when that element is clicked. Normally, the ts-criteria is the same as the expression that is shown in the column, but it doesn't have to be. The ts-criteria can also be filtered using the normal AngularJS filter syntax. Tablesort includes three filters parseInt, parseFloat, and parseDate, but any filter can be used.
The ts-name attribute can be set to declare a unique name for an expression which will be used in the event fired when sorting has changed.
The ts-default attribute can be set on one or more columns to sort on them in ascending order by default.
To sort in descending order, set ts-default to "descending"
The ts-repeat attribute must be set on the element with ng-repeat.
` Alternatively, By default, the sorting will be done as the last operation in the ng-repeat expression. To override this behavior, use an explicit This will first select the first 10 items in This will first sort the rows according to your specification and then only show the first 10 rows. If the When changing sorting in the table, an event named CSS All table headings that can be sorted on is styled with the css class By default, the content for the empty table cell is set to The message can be customized for each table by specifying the To disable this feature, add the attribute Configuring Global Options Several options may be configured globally per-app. Here's an example of how to change an option By default, table filtering & pagination are supported, but not enabled so that you may use any UI and any 3rd party angular code to do these types of things. To set up these features, you must provide some configuration HTML string templates. These will be the default templates for filtering & pagination for all tables use in the same app unless that feature is specifically disabled on a per-table basis. Here is an example of one way to set up the templates for an app that uses bootstrap and the Angular-UI Bootstrap pagination directive var pagerString = " There are several tokens that can be used in the templates which will be replaced with the proper Angular expressions. | Token | Description | The name of the things listed in the table can be displayed in the filtering and pagination templates. They are named On a table just set the The plural version of the word will be automatically generated by adding Changing the item name will also update the "no data" display to be Note that expressions can be used for these properties as well. In the below example a translation filter is applied to localize text. There are a couple of ways to mark a column as filterable. One approach is to add the Another approach is to add the #### Customized Pagination Options Set the Set the If filtering or pagination has been configured globally, but you wish to disable either of these features per table you can set #### Customized Filtering To have a custom UI for filtering, build the UI around the table however you want and simply provide the If filtering has been globally configured it is probably a good idea to also set Certain libraries like Bootstrap allow for tables to become responsive when at a smaller screen size by wrapping it in a This can be configured globally with the To get the current view of the data in the table, pass something to the In the above example, the click function When running the It may be useful to customize how a particular column is sorted. For example, if a column can contain The function specified in the html
`ts-repeat-start and ts-repeat-end may be used to compliment the ng-repeat-start and ng-repeat-end directives.`html`
{{ item.Name }}
{{ item.Description }} tablesort directive as part of your ng-repeat expression. E.g.`html
`items and then sort them. Alternatively, you can insert an explicit tablesort in the pipe:`html
`ng-repeat expression contains a track by statement (which is generally a good idea), that expression willtablesort:sortOrder
be used to provide a stable sort result.
Events
------ will be emitted which contains an array of all current sorting definitions.`
These sorting definitions could be used to set up sorted data retrieval when using other directives that handle things like pagination or filtering.js${o.name} ${o.order ? 'ASC' : 'DESC'}
$scope.$on('tablesort:sortOrder', (event, sortOrder) => {
self.sortOrder = sortOrder.map(o => {
return ;`
});
});tablesort-sortable
---. The table headings that the table is currently sorted on is styled with tablesort-asc or tablesort-desc classes depending on the sort-direction. A stylesheet is included to show that it works, but you probably want to build your own."No Items"
Empty Tables
---, however it can be changed via the noDataText configuration option (see below). It is inserted as one spanning
all columns and placed inside a , which is placed at the top of each table.ts-no-data-text attribute on the same element as the ts-wrapper.`html
`ts-hide-no-data to the ts-repeat row:`html
`filterTemplate
---
| Property | Type | Default | Description |
|----------------------|-------------------|------------------------|-------------|
| |string |"" |HTML string template for filtering the table. _This will be included before the element with ts-wrapper specified on it._ See example above.|filterFunction
| |function |undefined |A function that will be called for every item being iterated over in the table. This function will be passed the object being iterated over as the first parameter. It should return a boolean value as to include the item or not. _(This can be overridden per-table)_|itemNameSingular
| |string |"item" |The default singular version of the name for the items being iterated over. _(This can be overridden per-table)_|itemNamePlural
| |string |itemNameSingular + "s"|The default plural version of the name for the items being iterated over. This just appends "s" to the singular name, which should work for most words in English. _(This can be overridden per-table)_|noDataText
| |string |"No " + itemNamePlural|The text that displays in the .showIfLast cell shown when a table is empty. _(This can be overridden per-table)_|wrappingElementClass
||string |"" |Wrap the element in a div with this class. If left blank, no element will wrap the table. _(This can be overridden per-table)_|paginationTemplate
| |string |"" |HTML string template for paging the table. _This will be included after the element with ts-wrapper specified on it._ See example above.|perPageOptions
| |array of number|[10, 25, 50, 100] |The options for how many items to show on each page of results. _(This can be overridden per-table)_|perPageDefault
| |number |perPageOptions[0] |The default number of items for show on each page of results. By default, it picks the first item in the perPageOptions array. _(This can be overridden per-table)_|`js`
angular
.module('myApp')
.config(['tableSortConfigProvider', function(tableSortConfigProvider){
tableSortConfigProvider.noDataText = "This table has nothing to show!";
tableSortConfigProvider.wrappingElementClass = "table-reponsive";
}
]);`$3
js`
angular
.module('myApp')
.config(['tableSortConfigProvider', function(tableSortConfigProvider){
var filterString = "";";
filterString += "";";
filterString += "";";
filterString += "";
filterString += "";
filterString += "
filterString += "
filterString += "
tableSortConfigProvider.filterTemplate = filterString;";";
pagerString += "Showing {{CURRENT_PAGE_RANGE}} {{FILTERED_COUNT === 0 ? '' : 'of'}} ";
pagerString += "{{TOTAL_COUNT | number}} {{TOTAL_COUNT === 1 ? ITEM_NAME_SINGULAR : ITEM_NAME_PLURAL}}";
pagerString += "{{FILTERED_COUNT | number}} {{FILTERED_COUNT === 1 ? ITEM_NAME_SINGULAR : ITEM_NAME_PLURAL}} (filtered from {{TOTAL_COUNT | number}})";
pagerString += " ";
pagerString += "
pagerString += "";";
pagerString += "";
pagerString += "
pagerString += "
tableSortConfigProvider.paginationTemplate = pagerString;
}
]);TOTAL_COUNT
|-----------------------|-------------------------------------------------------------------------------------------------------------|
| | The number for the total count of items in the table |FILTERED_COUNT
| | The number for the total count of items in the table after the filter has been applied |FILTER_STRING
| | The string used for the ng-model of the text filter |PER_PAGE_OPTIONS
| | The array of numbers for the various page size options |ITEMS_PER_PAGE
| | The number for the selected number of items to display per page (the selected item from PER_PAGE_OPTIONS) |CURRENT_PAGE_NUMBER
| | The number for the page that is currently being viewed |CURRENT_PAGE_RANGE
| | The number for the current viewable range of pages |ITEM_NAME_SINGULAR
| | The singular version of the name of the items being iterated over |ITEM_NAME_PLURAL
| | The plural version of the name of the items being iterated over |"items"$3
collectively and "item" individually by default, but this can be customized in the global config, and per-table to be more specific as to what is being listed.ts-item-name attribute on the same element as ts-wrapper. Set this as the singular version of the word, not the plural.`html
`"s" to the end of the singular word. The above example would produce "product" and "products" This should be fine for many words in English, but in the rare instances where it is not, a ts-item-name-plural attribute may also be specified.`html
`"No " + ITEM_NAME_PLURAL _unless_ the globally configured noDataText option is in a format other than the default.`html` ts-wrapper
ts-item-name="page.ITEM_NAME_SINGULAR' | translate"
ts-item-name-plural="'page.ITEM_NAME_PLURAL' | translate"
ts-no-data-text="'page.NO_PAYMENTS_MATCH_CRITERIA_MESSAGE' | translate">ts-filter$3
attribute to the element. The property specified in the ts-criteria attribute will be used to filter.`html`
Id
Name
Price
Quantity
Date Ordered
ts-filter
NOTE that the attribute is not needed if custom filtering using the ts-filter-function attribute.ts-filter-fields attribute to the same element as the ts-wrapper. This attribute takes a comma separated list of all the fields to which the filter should be applied.`html
`ts-per-page-options attribute on the same element that ts-wrapper is set on to override the options for the number of items available per page.ts-per-page-default attribute on the same element that ts-wrapper is set on to override the default number of items available per page.`html
`ts-display-filtering="false" and/or ts-display-pagination="false" on the same element as ts-wrapper`html
`ts-filter-function attribute with a function that will return a boolean for the item being iterated over. This attribute must be set on the same element as ts-wrapperts-display-filtering="false"ts-filter
NOTE that the attribute is not needed for custom filtering.`js`
$scope.data = [
{id:1, name:"Product A", enabled: false},
{id:2, name:"Product B", enabled: true},
{id:3, name:"Product C", enabled: true}
];
$scope.customFilterValue = "";
$scope.customFilterFn = function(item){
if($scope.customFilterValue == ""){
return true;
} else if($scope.customFilterValue === "false"){
return !item.enabled
} else {
return item.enabled
}
};
`html`
Id
Name
enabled
{{item.id}}
{{item.name}}
{{item.enabled}}
table-reponsiveWrapping The Table Element
class. If this is desired on a table using angular-tablesort this can become and issue if the filtering or pagination are used since they will also be inside of this wrapping element, which will cause some display issues.wrappingElementClass configuration option, or per-table with the ts-wrapping-element-class attribute`html
`ts-get-table-data-functionGetting Data Out of the Table
attribute. Whatever is passed in will be converted into a function.`
That function can then be passed as a parameter to a click event function, or anything else. Within the controller, just run that function and it will return the data in the table.html
`ng-click="getTableData(getDataFn)" would be handled like this:`js`
$scope.getTableData = function (getDataFn) {
var results = getDataFn(true, true, false);
console.log("data from table", results)
};getDataFn function, it accepts 3 boolean parameterstrue
1. When the data will come back in the same sort order as the table is currently displaying. When false the data will come back in the original sort order (pre-tablesort)true
2. When the data will only include items that match the current filters, which will match the current table display. When false all items in the table are included regardless of what is currently being filtered.true
3. When and pagination is enabled, the data will only return the currently viewed page of data. When false data from all pages will be returned.ts-order-by$3
numbers and strings, you may want the numbers to be sorted numerically and the strings to be sorted
lexicographically. To specify a custom sorting function, add a attribute to your`
header element:html`Name ts-order-by attibute should behave in the same way as a custom comparisonArray.prototype.sort`. See
function passed to
MDN
for more details.