Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS checkbox - model doesn't default to false

I have two checkboxes in my Angular JS form, like this...

<input id="isBackground" type="checkbox" ng-model="addTemplate.data.isBackground">
<input id="repeats" type="checkbox" ng-model="addTemplate.data.repeats">

If I tick both boxes then write the $scope to the console, both values are set to true, but if I only tick one of them then one appears in the $scope (set to true) and the other one is simply missing. It should be in the $scope and set to 'false' surely?

like image 557
jonhobbs Avatar asked Jan 26 '14 12:01

jonhobbs


2 Answers

A more flexible solution is to set a ng-init value, this works for dynamic proprieties as well as fixed, something that the accepted solution does not do.

<div class="checkbox">
    <label><input type="checkbox" value="" ng-init="formData[field.checkBox]=false" ng-model="formData[field.checkBox]">{{field.name}}</label>
</div>
like image 137
Astronaut Avatar answered Oct 23 '22 23:10

Astronaut


You can use ngTrueValue, and ngFalseValue. I have use 1/0 use it accordingly

<input id="isBackground" ng-true-vale="1" ng-false-value="0" type="checkbox" ng-model="addTemplate.data.isBackground">
<input id="repeats" ng-true-vale="1" ng-false-value="0" type="checkbox" ng-model="addTemplate.data.repeats">

From Docs

ngTrueValue: The value to which the expression should be set when selected.

ngFalseValue: The value to which the expression should be set when not selected.

OR

You can use ngChecked, If the expression is truthy, then special attribute "checked" will be set on the element

<input id="isBackground" ng-checked="addTemplate.data.isBackground == true" type="checkbox" ng-model="addTemplate.data.isBackground">
<input id="repeats" ng-checked="addTemplate.data.repeats == true" type="checkbox" ng-model="addTemplate.data.repeats">
like image 27
Satpal Avatar answered Oct 23 '22 23:10

Satpal