Mastering Web Application

(Rick Simeone) #1

Displaying and Formatting Data


Additionally AngularJS provides a catch-all property name: $. Using this wildcard
as a property name we can combine AND and OR logical operators. Let's say that
we want to search for a string match in all properties of a source object, but take into
account only not completed items. In this case a filtering expression could be re-
written as follows:


ng-repeat="item in backlog | filter:{$: criteria, done: false}"

It might happen that the combination of required search criteria is so complex that
it is not possible to express it using object's syntax. In this case a function can be
provided as an argument to the filter (so called predicate function). Such a function
will be invoked for each and every individual element of a source collection. The
resulting array will contain only elements for which the filtering function returns
true. As a slightly contrived example we could imagine that we want to see only
backlog items that are already completed and required over 20 units of effort. The
filtering function for this example is both easy to write:


$scope.doneAndBigEffort = function (backlogItem) {
return backlogItem.done && backlogItem.estimation > 20;
};

And use:


ng-repeat="item in backlog | filter:doneAndBigEffort"

Counting filtered results


Often at times, we would like to display a number of items in a collection. Normally
it is as simple as using the {{myArray.length}} expression. Things get a bit more
complicated while using filters as we would like to show the size of a filtered
array. A naive approach could consist of duplicating filters in both a repeater and a
counting-expression. Taking our last example of filtering in a repeater:


<tr ng-repeat="item in backlog | filter:{$: criteria, done: false}">

We could try to create a summary row like:


Total: {{(backlog | filter:{$: criteria, done: false}).length}}

This has obviously several drawbacks; not only code is duplicated but also the same
filters need to be executed several times in two different places, not ideal from the
performance standpoint.

Free download pdf