javascriptangularjsng-init

Creating a check and uncheck all function in Angular Js


I have few check boxes which I have been check already using ng-init

<div class="checkbox">
     <label>
      <input type="checkbox" ng-init="model.A='A'" ng-model="model.A" ng-true-value="'A'" ng-false-value="'nope'"/>A
     </label>
</div>
<div class="checkbox">
     <label>
      <input type="checkbox" ng-init="model.A='B'" ng-model="model.B" ng-true-value="'B'" ng-false-value="'nope'"/>B
     </label>
</div>
<div class="checkbox">
     <label>
      <input type="checkbox" ng-init="model.C='C'" ng-model="model.C" ng-true-value="'C'" ng-false-value="'nope'"/>C
     </label>
</div>

What I want is to create a function to make these check boxes check and uncheck when I check a seperate check box, link or a button. Can some one help me?


Solution

  • Its simple as below,

    create a link to toggle the checkboxes check status, Here i have created three links

    first one is for toggle the checkbox status, second one for uncheck all the checkboxes and last one for check all the checboxes.

    <a href="#" ng-click="toggleCheck()">toggle check</a> | <a href="#" ng-click="uncheckAll()">uncheck all</a> | <a href="#" ng-click="checkAll()">check all</a>
    

    click on uncheck will be handle like below,

    $scope.uncheckAll = function() {
        $scope.model.A = false;
        $scope.model.B = false;
        $scope.model.C = false;
    };
    

    assign a value which result in uncheck of the checkboxes.

    click on check all will be handle like below,

     $scope.checkAll = function() {
         $scope.model.A = 'A';
         $scope.model.B = 'B';
         $scope.model.C = 'C';
    };
    

    Assign the initial values that result in check status of the checkboxes.

    Toggle check like below, if A unchecked then all gonna uncheck other vice all are gonna check.

    $scope.toggleCheck = function() {
        if ($scope.model.A == false) {
            $scope.checkAll();
        } else {
            $scope.uncheckAll();
        }
    };
    

    here is a DEMO