Check All , UnCheck All - AngularJs

Code to check and uncheck all using angularjs

by Ernesto Rendon

HTML

<div>
    <ul ng-controller="checkboxController">
        <li>Check All
            <input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" />
        </li>
        <li ng-repeat="item in Items">
            <label>{{item.Name}}
                <input type="checkbox" ng-model="item.Selected" ng-click="setCheckAll(item)" />
            </label>
        </li>
    </ul>
</div>

JavaScript

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


    $scope.Items = [{
        Name: "Item one"
    }, {
        Name: "Item two"
    }, {
        Name: "Item three"
    }];
    $scope.checkAll = function () {
        if ($scope.selectedAll) {
            $scope.selectedAll = true;
        } else {
            $scope.selectedAll = false;
        }
        angular.forEach($scope.Items, function (item) {
            item.Selected = $scope.selectedAll;
        });

    };
        
    $scope.setCheckAll = function (item) {
        //
        // Check if checkAll should be unchecked
        //
        if ($scope.selectedAll && !item.Selected) {
            $scope.selectedAll = false;
        } 
        //
        // Check if all are checked.
        //
        var checkCount = 0;
        angular.forEach($scope.Items, function(item) {
            if(item.Selected) checkCount++;
        });
        $scope.selectedAll = ( checkCount === $scope.Items.length);
    };

});