3

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.