AngularJS, ngRepeat and default switch

When using ngRepeat, you can create 3 pairs of radio buttons using the following code:

<div ng-repeat="i in [1,2,3]"> <input type="radio" name="radio{{i}}" id="radioA{{i}}" value="A" checked> A <input type="radio" name="radio{{i}}" id="radioB{{i}}" value="B"> B </div> 

For some reason, only the last pair of switches generated by ngRepeat depends on the checked attribute.

Is this because of how AngularJS updates the view? Is there any way to fix this?

+6
source share
2 answers

Perhaps because when the browser displays switches (as ng-repeat expands), all your radio stations have the same name, that is, "name="radio{{i}}" angular has not yet expanded it, therefore, the checked property has not applied properly among all of them, so you will need to use ng-attr-name so that angular will add an extended name attribute later, so try: -

 <div ng-repeat="i in [1,2,3]"> <input type="radio" ng-attr-name="radio{{i}}" ng-attr-id="radioA{{i}}" value="A" checked> A <input type="radio" ng-attr-name="radio{{i}}" ng-attr-id="radioB{{i}}" value="B"> B </div> 

Or use ng-checked="true" so that the checked attribute is applied as the ng-checked directive expands. eg,

 <input type="radio" name="radio{{i}}" ng-attr-id="radioA{{i}}" value="A" ng-checked="true"> A 

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app> <div ng-repeat="i in [1,2,3]"> <input type="radio" ng-attr-name="radio{{i}}" ng-attr-id="radioA{{i}}" value="A" checked> A <input type="radio" ng-attr-name="radio{{i}}" ng-attr-id="radioB{{i}}" value="B"> B </div> </div> 
+11
source

Here milestone_data.index == selected cat id;

  <div ng-repeat="category in catData.categories" > <input type="radio" name="quality" id="{{category.title}}" ng-value="{{category.id}}" ng-model="milestone_data.index" > <span>{{category.title}}</span> </div> 
+1
source

Source: https://habr.com/ru/post/979869/


All Articles