Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to create a tree-like checkboxes like this :

  • o Master Tree -
    • o Tree 1
      • o Subtree 1
      • o Subtree 2
    • o Tree 2
      • o Subtree 1
      • o Subtree 2

where each 'o' is a checkbox and functions include :

  1. when a checkbox is clicked to check, all its children checkboxes it will be checked.
  2. when a checkbox is clicked to uncheck, all its children checkboxes it will be unchecked
  3. when a checkbox is clicked to uncheck, all its parent checkboxes it will be unchecked since it will not be 'select all'

What I've tried:

  1. ng-model & ng-changed in all trees - although this is not ideal.

    Select All Below
    Child
    Grandchid 1
    Grandchid 2

    Demo

    function Ctrl($scope) {
    $scope.billing_is_shipping = true;
    
    $scope.master = true;
    $scope.child = true;
    $scope.grandchlid = true;
    
    $scope.checked = function (type) {
        switch (type) {
            case 'master':
                $scope.master = !$scope.master;
                if ($scope.master) {
    
                    $scope.child = true;
                    $scope.grandchild = true;
    
                } else {
    
                    $scope.child = false;
                    $scope.grandchild = false;
                }
                $scope.apply();
                break;
            case 'child':
                $scope.child = !$scope.child;
                if ($scope.child) {
                    $scope.grandchild = true;
    
                } else {
                    $scope.grandchild = false;
                }
                $scope.apply();
                break;
    
            case 'grandchild1':
                $scope.grandchild1 = !$scope.grandchild1;
                if(!$scope.grandchild1 || !$scope.grandchild2){
                     $scope.child = false;
                    $scope.master = false;
                }
                break;
    
        }
        console.log($scope.billing_is_shipping)
    }
    

    }

  2. ng-model or ng-changed only

    Demo

I've tried $scope.apply() and without but I can only get the first clicks to work and then everything just gives up.

Any approach or help would be greatly appreciated, and thanks in advance.

share|improve this question

1 Answer 1

I just wrote a directive on this, with which you could have as many levels of checkboxes as you like. Basically it checks recursively the logic you described above. Check out the repo, and the live demo.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.