Check All, UnCheck All - AngularJs

Code to select and unselect all using angularjs. Master checkbox reflects if sub checkboxes are all selected.

by gauravsingh

HTML

<div ng-controller="checkboxController">

  <label>
    <input type="checkbox" ng-model="selectedAll" ng-click="selectAll()" />
    Countries
  </label>

  <ul>
    <li ng-repeat="item in Items | orderBy:'name'">
      <label>
        <input type="checkbox" ng-model="item.Selected" ng-click="checkIfAllSelected()" /> {{item.name}}
      </label>
    </li>
  </ul>
</div>

JavaScript

angular.module("CheckAllModule", [])
  .controller("checkboxController", function checkboxController($scope) {

    $scope.Items = [{
      name: 'India'
    }, {
      name: 'USA'
    }, {
      name: 'Russia'
    }, {
      name: 'China'
    }, {
      name: 'Australia'
    }, {
      name: 'Japan'
    }];

    // select all items
    $scope.selectAll = function() {
      angular.forEach($scope.Items, function(item) {
        item.Selected = $scope.selectedAll;
      });
    };

    // use the array "every" function to test if ALL items are checked
    $scope.checkIfAllSelected = function() {
      $scope.selectedAll = $scope.Items.every(function(item) {
        return item.Selected == true
      })
    };


  });