Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs Checkbox that will toggle selected on all other checkboxes

I am using AngularJs (Angular 1) and I need to use a checkbox to Select / Unselect all other checkboxes.

Right now I have this:

<li ng-repeat="item in ctrl.items">
   <input type="checkbox" ng-model="item.selected">{{item.name}}
</li>

Then I have this in the controller:

ctrl.items = [
    {
        value: 0,
        name: 'Select All / Unselect all other checkboxes',
        selected: true
    },
    {
        value: 1,
        name: 'myCheckbox1',
        selected: true

    },
    {
        value: 2,
        name: 'myCheckbox2',
        selected: true

    },
    {
        value: 3,
        name: 'myCheckbox2',
        selected: true

    }

];

How can I make it so that the first checkbox basically just selects / unselects all other checkbboxes?


1 Answers

angular.module('app',[]).controller('MyController', function(){
   var ctrl = this;
   
   ctrl.changed = function(item){            
      if(item.value == 0)
        for(var x of ctrl.items)
          x.selected = item.selected;
   }
   
   ctrl.items = [   
      {
          value: 0,
          name: 'Select All / Unselect all other checkboxes',
          selected: true
      },
      {
          value: 1,
          name: 'myCheckbox1',
          selected: true
      },
      {
          value: 2,
          name: 'myCheckbox2',
          selected: true
      },
      {
          value: 3,
          name: 'myCheckbox2',
          selected: true
      }
  ];
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app' ng-controller='MyController as ctrl'>
  <li  ng-repeat="item in ctrl.items">
     <input type="checkbox" ng-model="item.selected" ng-change='ctrl.changed(item)'>{{item.name}}
  </li>
</div>
like image 110
Slava Utesinov Avatar answered Feb 01 '26 19:02

Slava Utesinov