Mastering Web Application

(Rick Simeone) #1
Chapter 4

Our sorting example builds on top of the previous, filtering one, so now our backlog
list can be both filtered and sorted. With AngularJS it is surprisingly easy to combine
both filters to create interactive tables.


The orderBy filter was deliberately placed after the filter filter.
The reason for this is performance: sorting is more costly as compared
to filtering so it is better to execute ordering algorithm on a minimal
data set.

Now that the sorting works we just need to add icons indicating which field we
are sorting and whether it is ascending or descending. Once again the ng-class
directive will prove very useful. Here is the example of visual indicators for the
"name" column:


<th ng-click="sort('name')">Name
<i ng-class="{'icon-chevron-up': isSortUp('name'), 'icon-chevron-
down': isSortDown('name')}"></i>
</th>

The isSortUp and isSortDown functions are very simple and look like:


$scope.isSortUp = function (fieldName) {
return $scope.sortField === fieldName && !$scope.reverse;
};

$scope.isSortDown = function (fieldName) {
return $scope.sortField === fieldName && $scope.reverse;
};

Of course there are many ways of displaying sort indicators, and the one just
presented strives to keep CSS classes out of JavaScript code. This way presentation
can be easily changed just be tweaking a template.


Writing custom filters – a pagination example


So far we've managed to display backlog items in a dynamic table that support
sorting and filtering. Pagination is another UI pattern that is often used with larger
data sets.


AngularJS doesn't provide any filter that would help us to precisely select a subset
of an array based on start and end indexes. To support pagination we need to create
a new filter, and this is a good occasion to get familiar with the process of writing
custom filters.

Free download pdf