JSFiddle - React, Tailwind, and code Playground

by Guddu Kumar

HTML

<div ng-app="" ng-controller="AppCtrl">
    <p><b>Dynamically generated checkbox with dynamic ng-models:</b></p>
    <br />

    <div ng-repeat="slave in slaves">
        <input type="checkbox" ng-model="slave.isChecked" ng-click="select($index)" /> {{ slave.name }} -  {{ slave.description }} </div>
    
    {{ checkboxData }}</div>

JavaScript

function AppCtrl($scope) {

    $scope.checkboxData = {};
    
    $scope.select = function(index){
        if(index === 0){
        debugger
            $scope.slaves.forEach(function(slave, ind){
                $scope.slaves[ind].isChecked = $scope.slaves[0].isChecked;
            });
        }
        else {
            var anyChild = false;
            for(var i = 1; i < $scope.slaves.length; i++){
                anyChild = anyChild || $scope.slaves[i].isChecked; 
            }
            $scope.slaves[0].isChecked = anyChild;
        }
    }

    $scope.slaves = [{
        name: 'Parent',
        type: 'parent',
        description: 'This needs to be checked when a child is selected and unchecked when no child is selected',
        isChecked: false
    }, {
        name: 'One',
        type: 'child',
        description: 'child',
        isChecked: false
    }, {
        name: 'Two',
        type: 'child',
        description: 'child',
        isChecked: false
    }, {
        name: 'Three',
        type: 'child',
        description: 'child',
        isChecked: false
    }, {
        name: 'Four',
        type: 'child',
        description: 'child',
        isChecked: false
    }];

    // I tried this JS method but it only works for static lists and by adding clickOthers() to each checkbox. But dont know how to do it for dynamic lists with many child checkboxes    
    $scope.clickOthers = function () {
        $scope.parentCheckbox = $scope.childCheckbox;
    }
}