I prefer to use the ngModel and ngChange directives when dealing with checkboxes. ngModel allows you to bind the checked/unchecked state of the checkbox to a property on the entity:
<input type="checkbox" ng-model="entity.isChecked">
Whenever the user checks or unchecks the checkbox the entity.isChecked
value will change too.
If this is all you need then you don't even need the ngClick or ngChange directives. Since you have the "Check All" checkbox, you obviously need to do more than just set the value of the property when someone checks a checkbox.
When using ngModel with a checkbox, it's best to use ngChange rather than ngClick for handling checked and unchecked events. ngChange is made for just this kind of scenario. It makes use of the ngModelController for data-binding (it adds a listener to the ngModelController's $viewChangeListeners
array. The listeners in this array get called after the model value has been set, avoiding this problem).
<input type="checkbox" ng-model="entity.isChecked" ng-change="selectEntity()">
... and in the controller ...
var model = {};
$scope.model = model;
// This property is bound to the checkbox in the table header
model.allItemsSelected = false;
// Fired when an entity in the table is checked
$scope.selectEntity = function () {
// If any entity is not checked, then uncheck the "allItemsSelected" checkbox
for (var i = 0; i < model.entities.length; i++) {
if (!model.entities[i].isChecked) {
model.allItemsSelected = false;
return;
}
}
// ... otherwise ensure that the "allItemsSelected" checkbox is checked
model.allItemsSelected = true;
};
Similarly, the "Check All" checkbox in the header:
<th>
<input type="checkbox" ng-model="model.allItemsSelected" ng-change="selectAll()">
</th>
... and ...
// Fired when the checkbox in the table header is checked
$scope.selectAll = function () {
// Loop through all the entities and set their isChecked property
for (var i = 0; i < model.entities.length; i++) {
model.entities[i].isChecked = model.allItemsSelected;
}
};
CSS
What is the best way to... add a CSS class to the <tr>
containing the entity to reflect its selected state?
If you use the ngModel approach for the data-binding, all you need to do is add the ngClass directive to the <tr>
element to dynamically add or remove the class whenever the entity property changes:
<tr ng-repeat="entity in model.entities" ng-class="{selected: entity.isChecked}">
See the full Plunker here.