Salman Kazmi
Salman Kazmi

Reputation: 3248

Selecting multiple checkboxes in Angular on button click

I have a table in my HTML code in which the rows are generated by AngularJS ng-repeat. Each row contains a checkbox in the first column and other data in the corresponding columns. I am trying to mark all checkboxes as selected when this button which is present in another div is clicked.

<tbody>
  <tr ng-repeat="row in myObject track by $index" ng-class-even="'alternate-row'">
    <td name="checkbox">
      <input type="checkbox" ng-model="row.checked" ng-style="row.checkboxStyle" ng-click="setSelectedRow(row)" />
    </td>
    <td>{{ row.data1 }}</td>
    <td>{{ row.data2 }}</td>
  </tr>
</tbody>

The button is as follows:

<div class="btn-group">
	<button type="button" id="selectAll" class="btn btn-default" title="Select All" ng-click="selectAllGrid()">Select All</button>
</div>

A method is called on the click of the checkbox that adds that particular row to an array. How will that method be called if I mark the checkbox as checked on click of the button.

Upvotes: 0

Views: 2297

Answers (2)

Sai
Sai

Reputation: 2668

You can do like this:

<table>
    <tbody>
      <tr ng-repeat="row in myObject track by $index" ng-class-even="'alternate-row'">
        <td name="checkbox">
          <input type="checkbox" ng-model="row.checked" ng-style="row.checkboxStyle" />{{row.checked}}
        </td>
        <td>{{ row.data }}</td>
      </tr>
    </tbody>
  </table>


  <div class="btn-group">
    <button type="button" id="selectAll" class="btn btn-default" title="Select All" ng-click="selectAllGrid()">Select All</button>
  </div>

and in your controller:

app.controller('MainCtrl', function($scope) {
  $scope.allchecked  = false;

  $scope.selectAllGrid = function(){
    console.log($scope.allchecked);
    $scope.allchecked = !$scope.allchecked
   for(var i =0; i<$scope.myObject.length; i++) {
     $scope.myObject[i].checked = $scope.allchecked ;
   }
  }

  $scope.myObject = [
      {"data": "sdfsdf"},
      {"data": "asdfassafs"},
      {"data": "asesfrsaedfsadfsadsd"}
    ]
});

Working plunker here

Upvotes: 2

Vikash Kumar
Vikash Kumar

Reputation: 1718

use the directive ng-checked

<tbody>
  <tr ng-repeat="row in myObject track by $index" ng-class-even="'alternate-row'">
    <td name="checkbox">
      <input type="checkbox" ng-checked="checkAll" ng-model="row.checked" ng-style="row.checkboxStyle" ng-click="setSelectedRow(row)" />
    </td>
    <td>{{ row.data1 }}</td>
    <td>{{ row.data2 }}</td>
  </tr>
</tbody>

and in your button function

selectAllGrid(){
 $scope.checkAll=true;
}

Upvotes: 2

Related Questions