Search code examples
javascripthtmlcheckboxangularjstri-state-logic

How can I get angular.js checkboxes with select/unselect all functionality and indeterminate values?


I am looking for something exactly like these (tri-state checkboxes with "parents"). But using that solution wouldn't be elegant, as I do not depend on jQuery right now, and I would need to call $scope.$apply to get the model to recognize the automatically (un)checked checkboxed jQuery clicked.

Here's a bug for angular.js that requests ng-indeterminate-value implemented. But that still wouldn't give me the synchronization to all the children, which is something I don't think should be a part of my controller.

What I am looking for would be something like this:

  • A "ng-children-model" directive with syntax like: <input type="checkbox" ng-children-model="child.isSelected for child in listelements">. The list of booleans would be computed, and if 0 selected -> checkbox false. If all selected -> checkbox true. Else -> checkbox indeterminate.
  • In my controller, I would have something like this: $scope.listelements = [{isSelected: true, desc: "Donkey"},{isSelected: false, desc: "Horse"}]
  • The checkboxes would be made as usual with <tr ng-repeat="elem in listelements"><td><input type="checkbox" ng-model="elem.isSelected"></td><td>{{elem.desc}}</td></tr>.
  • As I understand it, the browser will determine which state a clicked indeterminate checkbox goes into.

Solution

  • Here's a refined version of Piran's solution. Using .prop() instead of .attr() fixes the checked issue.

    Usage:

    <div ng-repeat="elem in list">
        <input type="checkbox" ng-model="elem.isSelected" /> {{elem.desc}}
    </div>
    <ui-select-all items="list" prop="isSelected"></ui-select-all> Select all