forgottofly forgottofly - 11 months ago 75
AngularJS Question

select all checkboxes inside ng-repeat

Am having a list of check boxes in ng-repeat as:

<div ng-repeat="item in results">
<label class="inlinelabel checkbox">
<input type="checkbox" ng-model="selected[]"><i></i>

I would like to select all checkboxes on click of a single check box that is outside the ng-repeat.

<label> Select All </label>
<input type="checkbox" data-ng-model="selectedAll" ng-click="checkAll()">

I tried the code in controller but its not working.

if ($scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
angular.forEach($scope.employees,function (selected) {
selected[] = $scope.selectedAll;

Answer Source

The other answers here indeed make all the checkboxes "selected", but I think the idea is to make the underlying model also change, which those answers fail to do.

This is because Angular would not change the model when ng-checked changes. Instead, the right way to "select all" is to change the models - and the View just follows.

<button ng-click="selectAll()">select all</button>
<div ng-repeat="item in items">
    <input type="checkbox" ng-model="selected[]">

And in the controller, simply set all the items to be true in selected:

$scope.selected = {};
$scope.selectAll = function(){
  for (var i = 0; i < $scope.items.length; i++) {
    var item = $scope.items[i];

    $scope.selected[] = true;


The ViewModel "drives" the View (with the exception of the bi-directional directives, like ng-model, that allows the View to change the ViewModel, typically based on user interaction), so whenever you want to change something, start by asking yourself "how would I want the ViewModel to look like", rather than, how the View should look. The View will follow the ViewModel.