Tree checkboxes in AngularJS
I am trying to create tree checkboxes like:
- o Master tree -
- o Tree 1
- o Subtree 1
- o Subtree 2
- o Tree 2
- o Subtree 1
- o Subtree 2
- o Tree 1
where each "o" is a checkbox and the functions include:
- when a checkbox is checked to check, all of its child checkboxes will be checked.
- when a checkbox is checked to uncheck the checkbox, all of its child checkboxes will be unchecked.
- when a checkbox is checked to uncheck a checkbox, all of its parent checkboxes will be unchecked since it will not "select all"
What I have tried:
-
ng-model and ng-changed in all trees - although not ideal.
Select all below
Child
Grandchid 1
Grandchid 2function 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) }
}
-
ng-model or ng-changed only
I've tried $ scope.apply () and without it, but I can get the first clicks to work and then everything just gives up.
Any approach or help would be greatly appreciated and thanks in advance.
+3
source to share
1 answer
I just wrote a directive about this, with which you could have as many checkbox levels as you like. It basically checks the logic above recursively. Look repo and live demonstration .
+1
source to share