Chinmay235
Chinmay235

Reputation: 3414

AngularJS radio button value not changed while change my choice

var myApp = angular.module('myApp', []);
myApp.controller("SomeController", function($scope) {
    $scope.formData = {};
    $scope.choices = [
    {
      "text": "Denim",
      "price": "$0.00",
      "isSelected": "false"
    }
      ,
      {
        "text": "Black",
        "price": "$0.00",
        "isSelected": "true"
      },
      {
        "text": "Brown",
        "price": "$0.00",
        "isSelected": "false"
      }];
      
      $scope.formData = $scope.choices;
        
    $scope.save = function(){
      $scope.formData = $scope.choices;
    };
	});
    
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<div>Choose your choice</div>
<div ng-app="myApp" ng-controller="SomeController">
  <div ng-repeat="choice in choices">
    <input type="radio" id="choicesRadio{{$index}}" name="choicesRadio" ng-model="choice.isSelected" value="true" /> <label for="choicesRadio{{$index}}">{{choice.text}}</label>
  </div>
    <!--<input type="button" ng-click="save()" value="Submit" />-->
   <pre>{{formData | json}}</pre>
</div>

   

I have 3 choices Denim, Black and Brown default checked Black while page load. When I am changing Black to Denim my previous Black option isSelected value not changed. Pleas check code snippet and let me know how to make any one true rest will change to false

Thank you.

JSFIDDLE

Upvotes: 0

Views: 375

Answers (2)

Pradeepb
Pradeepb

Reputation: 2562

Hope this solution helps you.

HTML code

<div ng-repeat="choice in choices">
     <input type="radio" id="choicesRadio{{$index}}" name="choicesRadio" ng-model="choice.isSelected" ng-value="true" ng-click="setChoice(choice)" /> <label for="choicesRadio{{$index}}">{{choice.text}}</label>
</div>

Code in controller

$scope.setChoice = function (c) {
   angular.forEach($scope.choices, function (c) {
        c.isSelected = false;
   });
   c.isSelected = true;
};

Upvotes: 1

M.Be
M.Be

Reputation: 322

With angular, the right way to declare input is not to put them into a ng-repeat.

You need to put the "ng-repeat-start" and "ng-repeat-end" ;) Try the following : (not validate on plunker but should work)

<input type="radio" ng-repeat-start="choice in choices" id="choicesRadio{{$index}}" name="choicesRadio" ng-model="choice.isSelected" value="true" /> 
<label for="choicesRadio{{$index}}" ng-repeat-end>{{choice.text}}</label>

In fact, the previous snippet is working like yours. I just realize that you have an attribute "value" identical for all your option.

So, when you click, angular just set "true" in the variable binded with "ng-model". So, you put "true" on each click, but nothing more.

If you want to know wich one is check, take a fix variable for your "ng-model" attribute, not one wich will change with your option.

(i will try to edit your jsfiddle)

Upvotes: 0

Related Questions