So, the very best way to solve this problem has three parts. We need to bind the checked
attribute and the indeterminate
attribute, and we need to handle the change event.
First, we want the checkbox to be checked whenever the selected
array has all the items in the items
array. So:
<input type="checkbox" checked.bind="selected.length === items.length" />
This checks the checkbox whenever all items are selected, but checking the checkbox has no effect on the selected
array yet.
Next, we want the checkbox to be indeterminate whenever selected
array has some but not all items in the items
array. So:
<input type="checkbox
checked.bind="selected.length === items.length"
indeterminate.bind="selected.length > 0 && selected.length < items.length" />
Now, the checkbox completely reflects the state of the selected
array, but still has no effect on the selected
array.
Finally, we can listen to the change
event on the checkbox to update the selected
array whenever the checkbox is checked or unchecked. I use an inline handler below, and in this handler $event.target
is the checkbox itself.
<input type="checkbox"
checked.bind="selected.length === items.length"
indeterminate.bind="selected.length > 0 && selected.length < items.length"
change.delegate="$event.target.checked ? selected = items.slice() : selected = []" />
At this point, the checkbox is working perfectly. Checked is normally a two-way binding, but in our example above it is only operating one-way. We can make this small optimization:
<input type="checkbox"
checked.one-way="selected.length === items.length"
indeterminate.one-way="selected.length > 0 && selected.length < items.length"
change.delegate="$event.target.checked ? selected = items.slice() : selected = []" />
See this gist.run for a working example: https://gist.run/?id=61cc823708ff7f6ba195de9ff0353049
Note that I typically find it useful to create a custom element that encapsulates this behavior.