Search code examples
angularjscheckboxangularjs-ng-repeatangular-ng-if

Select checkbox ng-if parent checkbox is slected, both parent & child is uncountable diff. array


Structure is

$scope.divisions = [
  { Description: 'test1', Id: 1 },
  { Description: 'test2', Id: 2 },
  { Description: 'test3', Id: 3 },
  { Description: 'test4', Id: 4 },
  { Description: 'test5', Id: 5 }
];

  $scope.subd = [
  { Description: 'sub1', Id: 7 },
  { Description: 'sub2', Id: 8 },
  { Description: 'sub3', Id: 9 }
];

If test1 is selected subd should display under that,subd can be selectable.

I wants to catch only id of division and subd.

check it on Plunker http://plnkr.co/edit/hjb5HTITyJelqdjLN5h2?p=preview


Solution

  • Update

    If you want the parent to be selected just only when one or more children are selected then you might consider disabling parent input and update it based upon selected children.

    Also store them on a new variable $scope.selected as json.

    <ul class="radio-check-group">
        <li ng-repeat="d in divisions">
          <input disabled type="checkbox" ng-model="d.selected" class="" id="{{'div' + d.Id}}" name="selectedDivisions[]" />
          <label for="div{{$index}}">{{d.Description}}</label>
          <ul>
            <li ng-repeat="s in d.subd">
            {{$parent.$index}}
              <input type="checkbox" ng-change="updateParent(d)" ng-model="s.selected" class="" id="{{'div' + d.Id}}" name="selectedsubd[]" />
              <label for="div{{$index}}">{{s.Description}}</label>
            </li>
          </ul>
        </li>
      </ul>
    

    And controller function:

    function initializeDivisionSubd() {
        angular.forEach($scope.divisions, d => {
            d.subd = angular.copy($scope.subd);
        })
    };
    
    $scope.selected = [];
    
    initializeDivisionSubd();
    
    $scope.updateParent = (parent) => {
        parent.selected = !!parent.subd.find(s => s.selected);
        $scope.selected = angular.toJson($scope.divisions.filter(d => d.selected).map(d => {
          return {
            Id: d.Id,
            subd: d.subd.filter(sd => sd.selected).map(sd => {
              return {
                Id: sd.Id
              }
            })
          }
        }));
    

    Here's the updated fiddle