Indeterminate (Tri-State) Checkbox Directive

2,830 views
Skip to first unread message

Chris Waguespack

unread,
May 9, 2013, 10:39:27 AM5/9/13
to ang...@googlegroups.com
I'm trying to implement an indeterminate (tri-state) checkbox directive based on the examples at http://stackoverflow.com/questions/12648466/how-can-i-get-angular-js-checkboxes-with-select-unselect-all-functionality-and-i. What I have so far is at http://jsfiddle.net/cjwprostar/M4vGj/. One problem that I'm running into is that updating the 'checked' property of the parent checkbox (in the $watch on the child list) doesn't send a change event to let the model know it needs to update. (Try unchecking the parent checkbox then check each of the children and notice that "All eaten" stays false)

So then, a few questions:
  1. What do I need to do to have the model on the parent checkbox update? Do I need to dispatch a change event? Tie in ngModel into my directive? Something else?
  2. Is there a way to force this directive to only be used on Angular checkbox inputs? (like maybe throwing an exception if the element doesn't use the input directive and the type isn't checkbox)
  3. How could this directive could be improved to increase reusability/flexibility?
I'm still new to Angular and this is the first directive I've tried to create, so any help would be appreciated. Thanks!

pingt...@gmail.com

unread,
May 9, 2013, 11:13:04 AM5/9/13
to ang...@googlegroups.com
There may be a better way, but the following seems to be the simplest: http://jsfiddle.net/nvYGP/

Chris Waguespack

unread,
May 9, 2013, 2:41:24 PM5/9/13
to ang...@googlegroups.com
Wow, I can't believe it was that simple! Thanks for the help.

Chris Waguespack

unread,
May 9, 2013, 6:22:01 PM5/9/13
to ang...@googlegroups.com
I ran into an issue when the model was set to a nested object (like person.allEaten). I looked into it some more and figured out that requiring ngModel and using $setViewValue was another way to handle the issue. I made an updated example at http://jsfiddle.net/cjwprostar/M4vGj/6/.

Jason Sobell

unread,
May 9, 2013, 8:19:54 PM5/9/13
to ang...@googlegroups.com
Nice. I wish it was easier to find these solutions. I didn't notice $setViewValue in the doco :)
Reply all
Reply to author
Forward
Message has been deleted
0 new messages