Toggle all Angular checkboxes into a group

I have a table of text elements, each of which contains a description and a checkbox. Now I need to add an uber-checkbox that will either clear or mark all the fields. The current code is shown below when my first attempt to highlight the solution.

<table width="100%" border="0" cellspacing="0" cellpadding="0" class="table table-bordered"> <tr id="myBlusteringAttempt"> <td width="90%"> <p>Clear/Check all options</p> </td> <td width="10%" align="center" valign="middle"> <input type="checkbox" ng-change="toggleCheckboxes()"> </td> </tr> <tr id="existing-code-that-works" ng-repeat="declaration in LegalDeclaration.ReplacementOfPolicy.ReplacementPolicyDeclarations"> <td width="90%"> <p>{{declaration.DeclarationText}}</p> </td> <td width="10%" align="center" valign="middle"> <input type="checkbox" ng-model="declaration.AcceptDeclaration"> </td> </tr> </table> 

Perhaps I could have done this with jQuery so easily, but I would have preferred to use the Angular jQuery facade and prevent the framework from being used improperly.

+5
source share
2 answers

First of all, you need to set the ng-model checkbox to switch in order for this to work, otherwise Angular may complain :

 <input type="checkbox" ng-model="toggle" ng-change="toggleCheckboxes()"> 

Then you should loop the results and bind them to the checkbox value:

  $scope.toggle = false; $scope.toggleCheckboxes = function () { angular.forEach($scope.LegalDeclaration.ReplacementOfPolicy.ReplacementPolicyDeclarations, function (value, key) { value.AcceptDeclaration = $scope.toggle; }); } 

Full working example

Example code above

Edited I should notice that your approach to switching user interface elements as checkboxes is different from the Angular area. Angular is mainly used as an MV * database with a database binding, fetching data into your view. You should learn more about using Angular (or any other MV * framework like Backbone): "Thinking in AngularJS" if I have jQuery background?

0
source

In toggleCheckboxes you just need to set all the models to the right value.

 var currentAllStatus = false; $scope.toggleCheckboxes = function () { currentAllStatus = !currentAllStatus; $scope.LegalDeclaration.ReplacementOfPolicy.ReplacementPolicyDeclarations.forEach(function (declaration) { declaration.AcceptDeclaration = currentAllStatus; }); }; 
+1
source

All Articles