7

I was trying to use checkbox and bind the checked attribute using ng-checked attribute but its not working where as its working fine with ng-model attribute with checkbox type inputs.

<!-- not working -->
<input type="checkbox" name="checkedBox"
                       id="checkedBox11"
                       ng-checked="isChecked">

<!--working-->
<input type="checkbox" name="checkedBox"
                       id="checkedBox21"
                       ng-model="isChecked">

I have created a jsbin to demonstrate the same: here

2 Answers 2

6

Since you are not connecting the checkbox with a model in the first case, it is not getting changed in angular and hence the value is not changing in the view also.

However,in the second case, you have attached the isChecked to the checkbox, the changes are reflecting.

Update: If you change the default value of isChecked to true, it shows true and the checkbox is also checked on load.

Sign up to request clarification or add additional context in comments.

2 Comments

in both cases model is getting binded since as in my jsbin example when I click on lower checkboxes the upper also toggles thus model is getting binded. What I wanted to know is why ng-checked not working here as shown in angular sample codes.
@guleria No, in the first case the value of the model is getting binded to the state (checked or not checked) of the checkbox while in the second case, the checkbox itself is getting binded to the model so that a change in the checkbox triggers a change in the model. The reason that on changing the lower checkboxes, the upper boxes also change is because as the value of the isChecked changes, an apply is called internally by angular and where ever isChecked is used, the value is updated.
2

Changing the first input to have model, changes it. You could also use ng-click to change the value. (addming ng-model="isChecked")

<input ng-model="isChecked" type="checkbox" name="checkedBox" id="checkedBox11" ng-checked="isChecked"> 

Or you could add ng-click="isChecked=!isChecked" to the checkbox

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.