Manoj Shrestha
Manoj Shrestha

Reputation: 4694

AngularJS radio button groups with name attribute not initializing properly

The radio buttons group doesn't seem to initialize property inside a ng-repeat block if we specify the name attribute to the group. It seems working for the last set of radio groups, but not for the rest. Also, it works fine if I remove the name attribute. Per [AngularJS documentation][1], the name attribute is not needed if we use it with ngModel. But it doesn't say we must not use it. And I need to specify a name attribute.

Please refer to the example below:

var m = angular.module("MyApp", []);

m.controller("MyController", ["$scope", function($scope) {
  
  $scope.myArr = [{
    name: "Obj 1",
    status: "a"
  }, {
    name: "Obj 2",
    status: "b"
  }, {
    name: "Obj 3",
    status: "c"
  }];
}]);
body {
  background-color: #1D1F20;
}
 
.row {
  margin-bottom: 15px;
}

.demo {
  background: green;
  color: white;
  padding: 10px;
  border-radius: 3px;
  min-width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyController" class="demo">
    <div ng-repeat="eachItem in myArr" class="row">
        
        <span>{{eachItem.name}} => </span>
        
        <label> a
          <input name="status-$index" type="radio" ng-model="eachItem.status" value="a">
        </label>
        
        <label> b
          <input name="status-$index" type="radio" ng-model="eachItem.status" value="b">
        </label>
        
        <label> c
          <input name="status-$index" type="radio" ng-model="eachItem.status" value="c">
        </label>
        
    </div>
</div>

Upvotes: 0

Views: 34

Answers (1)

nircraft
nircraft

Reputation: 8478

Your code looks fine except the place where you are setting the name attribute to input.

$index in template will be evaluated only if you enclose it inside curly brackets. EX: {{$index}} else you will get $index in the name. You should use:

 <div ng-repeat="eachItem in myArr track by $index" class="row">
   <input name="status-{{$index}}" type="radio" ng-model="eachItem.status" value="a">...
 </div>

Upvotes: 1

Related Questions