Mastering Web Application

(Rick Simeone) #1
Chapter 4

This example is interesting since we are using the ng-controller directive for each
item. A provided controller can augment scope with functions and variables to
control selection state:


.controller('UserCtrl', function ($scope) {

$scope.toggleSelected = function () {
$scope.selected = !$scope.selected;
};

$scope.isSelected = function () {
return $scope.selected;
};
});

It is important to understand that specifying a controller on the same DOM element
as the ng-repeat directive means that the controller will be managing a new scope
created by a repeater. In practice it means that we can have a controller dedicated to
managing individual items of a collection. It is a powerful pattern that allows us to
neatly encapsulate item-specific variables and behavior (functions).


Altering tables, rows, and classes

Zebra-striping is often added to lists in order to improve their readability. AngularJS
has a pair of directives (ngClassEven and ngClassOdd) that make this task trivial:


<tr ng-repeat="user in users"
ng-class-even="'light-gray'" ng-class-odd="'dark-gray'">

...



The ngClassEven and ngClassOdd directives are just specialization of the more
generic ngClass directive. The ngClass is very versatile and can be applied in
many different situations. To demonstrate its power we could rewrite the preceding
example like follows:


<tr ng-repeat="user in users"
ng-class="{'dark-gray' : !$index%2, 'light-gray' : $index%2}">

Here the ngClass directive is used with an object argument. Keys of this object
are class names and values; conditional expressions. A class specified as a key
will be added or removed from an element based on result of a corresponding
expression evaluation.

Free download pdf