Mastering Web Application

(Rick Simeone) #1

Displaying and Formatting Data


<tr ng-switch-when="true">
<td colspan="2">{{user.desc}}</td>
</tr>
</tbody>
</table>

In the preceding example an additional row, containing user details, is only rendered
if a given user was selected. A selection process is very simple and is covered by the
selectUser and isSelected functions:


.controller('ListAndOneDetailCtrl', function ($scope, users) {
$scope.users = users;

$scope.selectUser = function (user) {
$scope.selectedUser = user;
};

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

Those two functions take advantage of the fact that there is one scope (defined on top
of the table DOM element) where we can store a pointer (selectedUser) to an active
item of a list.


Displaying many rows with details


Assuming that we would like to allow multiple rows with additional details we need
to change a strategy. This time selection details need to be stored on each and every
element level. As you remember the ng-repeat directive is creating a new scope for
each and every element of a collection it iterates over. We can take advantage of this
new scope to store "selected" state for each item:


<table class="table table-bordered">
<tbody ng-repeat="user in users" ng-controller="UserCtrl"
ng-click="toggleSelected()" ng-switch on="isSelected()">
<tr>
<td>{{user.name}}</td>
<td>{{user.email}}</td>
</tr>
<tr ng-switch-when="true">
<td colspan="2">{{user.desc}}</td>
</tr>
</tbody>
</table>
Free download pdf