1

This is AngularJS I write.

<script type="text/javascript">
    var app = angular.module("App1", []);
    app.controller("ctrl1", function ($scope, $filter) {
        $scope.GenderChoice = ["Male","Female"];
    });
</script>

This code below is work. "Gender" changes value when i change radio button.

<input id="MaleOption" name="oo" type="radio" ng-model="Gender" value="{{GenderChoice[0]}}" />
    <input id="FemaleOption" name="oo" type="radio" ng-model="Gender" value="{{GenderChoice[1]}}" />

I want to use ng-repeat with radio button. This code below is not work. When i click change radio button, "Gender" is not response. Actually, "Gender" never shows the value.

<input ng-repeat="x in GenderChoice" id="{{x}}Option" name="oo" type="radio" ng-model="Gender" value="{{x}}" />

This code below is not work too.

<input ng-repeat="x in GenderChoice" id="{{x}}Option" name="oo" type="radio" ng-model="Gender" value="{{GenderChoice[$index]}}" />

What wrong with these code. Thank for advance.

2 Answers2

0

ng-repeat creates a new scope for each iteration. Due to the way that JavaScript Prototype Inheritance affects Angular, and the fact that you are binding to a primitive rather than an object, you actually have two separate Gender properties, and the radio buttons are not interconnected.

The preferred way to solve this would be to bind to a property on an object (the "Always use a dot in your bindings" rule), which will automatically imply the same object for both buttons. i.e.

app.controller("ctrl1", function ($scope, $filter) {
    $scope.GenderChoice = ["Male","Female"];
    $scope.selected = {};
});

<input ng-repeat="x in GenderChoice" 
       id="{{x}}Option" name="oo" type="radio" 
       ng-model="selected.Gender" value="{{x}}" />
Community
  • 1
  • 1
Claies
  • 22,124
  • 4
  • 53
  • 77
0

look at this pice of code it's all what you need

<style>

  .green {
    color: green;
    }

  .red {
    color: red;
  }
</style>
    <input ng-repeat="x in GenderChoice" 
  id="{{x}}Option" name="oo" type="radio" ng-model="Gender" value="{{x}}" ng-click="class(Gender)"/>
     <p class={{append}}>{{gender}}</p>

you need to submit Gender to access its value

 var app = angular.module("App1", []);
 app.controller("ctrl1", function ($scope, $filter) {
    $scope.GenderChoice = ["Male","Female"];
    $scope.class = function(x){
      if (x == 'Male') {
        $scope.append = 'green';
        $scope.gender = 'Male';
      }
      if (x == 'Female') {
        $scope.append = 'red';
        $scope.gender = 'Female';
      }
    }
});

working plunker

Arashk
  • 617
  • 5
  • 16