简体   繁体   中英

Radio buttons are not checked initially

I have seen a lot of similar questions but none of them could solve my problem:

I have a ng-repeat to show list of items. And each of them has a div which is shown when some condition is met: ' <div ng-if="someCondition"> </div>

And inside that div, i have a radio button:

<input type="radio" ng-model="item.Prop" name="published" ng-value="true" ng-checked="item.Prop"> <span>published</span>
<input type="radio" ng-model="item.Prop" name="published" ng-value="false"> <span>not published</span>

While other functionalities are working, it is not directly checked when my div becomes visible. However, if i select one of them, it changes its ng-model.

But why is that not selected at the beginning?

Hard to know based on the code you provided, but I'm guessing item.Prop is undefined . If you provide us with more code, a fiddle or a plunker, we may be able to help more.

Example fiddle demonstrating the behaviour you're experiencing: http://jsfiddle.net/HB7LU/20982/

Example fiddle with the checkbox working as you'd wish: http://jsfiddle.net/HB7LU/20983/

I have found the solution:

The problem was that checkboxes are created for each item in the ng-repeat loop. So, every checkbox has the same name and therefore none of them could be selected.

To solve it, i have just given an unique property of items at the end of the names of checkboxes.

<input type="radio" ng-model="item.Prop" name="published{{item.ID}}" ng-value="true" ng-checked="item.Prop"> <span>published</span>
<input type="radio" ng-model="item.Prop" name="published{{item.ID}}" ng-value="false"> <span>not published</span>

Here is the plunker :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM