I have a checkbox inside button:
<button ng-mousedown="active = !active">
<input type="checkbox" ng-checked="active"/>
Toggle!
</button>
Clicking the button toggles state variable "active"
. I want to sync the checkbox with "active"
. If I declare
ng-model="active",
the box is in sync with the button as long as the button is pressed outside the checkbox.
The problem is when the checkbox is clicked, it changes the state but also sends click event to the button, so both events fire and as a result, the box bees out of sync:
The sync behaviour is restored when using ng-click
instead of ng-mousedown
, however, I prefer to use the latter as this way it feels more responsive (the button reacts faster).
Is there any (Angular) way I can keep the box in sync and keep the ng-mousedown
?
I have a checkbox inside button:
<button ng-mousedown="active = !active">
<input type="checkbox" ng-checked="active"/>
Toggle!
</button>
Clicking the button toggles state variable "active"
. I want to sync the checkbox with "active"
. If I declare
ng-model="active",
the box is in sync with the button as long as the button is pressed outside the checkbox.
The problem is when the checkbox is clicked, it changes the state but also sends click event to the button, so both events fire and as a result, the box bees out of sync:
http://jsbin./wepul/7/edit
The sync behaviour is restored when using ng-click
instead of ng-mousedown
, however, I prefer to use the latter as this way it feels more responsive (the button reacts faster).
Is there any (Angular) way I can keep the box in sync and keep the ng-mousedown
?
-
input
is invalid child ofbutton
– charlietfl Commented Aug 12, 2014 at 13:32 - and keeping checkbox disabled is not an option, right ? – coder Commented Aug 12, 2014 at 13:35
- @charlietfl In what sense invalid? It works fine. – Dmitri Zaitsev Commented Aug 12, 2014 at 14:22
- @coder disabling would make it look disabled, which is would be confusing, the checkbox should be functional – Dmitri Zaitsev Commented Aug 12, 2014 at 14:33
-
I would use
label
instead ofbutton
and you wouldn't need theng-mousedown
since label will always changecheckbox
– charlietfl Commented Aug 12, 2014 at 14:46
2 Answers
Reset to default 7If you use the default behavior of <label>
around a checkbox instead of <button>
you can simplify any need for extra event handling. When a label is clicked it will automatically change any radio or checkbox within it
<label ng-class="{active: active1}" >
<input type="checkbox" ng-model="active1"/>
Change ng-checked!
</label>
DEMO
try this
<button ng-class="{active: active1}" ng-mousedown="active1 = !active1">
<input type="checkbox" ng-model="active1" ng-change="active1=!active1"/>