Patrick Patrick - 3 months ago 24
AngularJS Question

Check All checkbox function inside a modal

If user clicks 'add data' a modal opens, I have individual checkboxes for data1,data2,data3,data4. I also have a check all checkbox. If user clicks this, it should be able to select all above 4, if clicks again, it should deselect all. Also, once selected, the value of 'Select All' should change to 'Deselect All'

Code:

<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">

<div class="modal-body">
<label><input type="checkbox" ng-model="checkboxModel.value1"> Data1</label><br/>
<label><input type="checkbox" ng-model="checkboxModel.value2"> Data2</label><br/>
<label><input type="checkbox" ng-model="checkboxModel.value3"> Data3</label><br/>
<label><input type="checkbox" ng-model="checkboxModel.value4"> Data4</label><br/>
<label><input type="checkbox" ng-model="checkboxModel.value5">Select All</label><br/>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="ok()">OK</button>
<button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
</div>
</script>

<button type="button" class="btn btn-default" ng-click="open()">Add data</button>
</div>


Can someone let me know how to achieve this. I saw a lot of posts online but each had ng-repeat for the first 4 checkboxes. Mine is without using ng-repeat. Can someone please advise.

I have the following plunker: http://plnkr.co/edit/nSCGJzj1zG5SGO2N76L3?p=preview

Answer

I noticed that you were not binding to the items array. I fixed that by using the following markup:

   <div ng-repeat="item in items">
      <label>
        <input type="checkbox" ng-model="item.Selected">{{item.name}}</label>
      <br/>
    </div>
    <label>
      <input type="checkbox" ng-model="selectedAll" ng-click="checkAll()">Select All</label>
    <br/>

After that, I had to change the structure of the items property to become an object for later binding:

$scope.items = [{
name: 'item 1'
}, {
name: 'item 2'
}, {
name: 'item 3'
}, ];

To be able to update all the other checkboxes, I resorted to the following code:

$scope.checkAll = function() {

if ($scope.selectedAll) {
  $scope.selectedAll = true;
} else {
  $scope.selectedAll = false;
}
angular.forEach($scope.items, function(item) {
  item.Selected = $scope.selectedAll;
});

}

Please, refer to this plunker example for the full working solution.

UPDATE

enter image description here

Comments