Search code examples
javascripthtmlangularjscheckboxangular-directive

Keep checkbox unchecked until onclick function returns true with AngularJS


Using AngularJS framework, in my HTML code I have this checkbox:

<input type="checkbox" ng-checked="switch.isOn()" ng-click="SwitchController.setValue()"> 

When clicked, the checkbox is checked/unchecked before the setValue function get executed. I want the checkbox not to be checked if the setValue() function returns false value.


Solution

  • You can use ng-true-value and ng-false-value along with ng-model. If you get false value from your function just set the ng-model to constant you've specified in ng-false-value. Also you can use ng-disabled and set it true for the duration between right after entering the SwitchController.setValue() and the same function returning the value to prevent unwanted clicks. This won't exactly delay the clicking of checkbox but should get you the desired end result.