更改我的选择时,AngularJS单选按钮值未更改

时间:2016-09-23 08:09:42

标签: angularjs

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>

   

我在页面加载时有3个选项DenimBlackBrown默认选中Black。当我将Black更改为Denim时,我之前的黑色选项isSelected值未更改。请检查代码段并让我知道如何让任何一个true休息时间更改为false

谢谢。

JSFIDDLE

2 个答案:

答案 0 :(得分:1)

希望此解决方案可以帮助您。

HTML代码

<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>

控制器中的代码

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

答案 1 :(得分:0)

使用angular,声明输入的正确方法不是将它们放入ng-repeat。

你需要把&#34; ng-repeat-start&#34;和&#34; ng-repeat-end&#34; ;) 请尝试以下操作:(不对plunker进行验证,但应该有效)

<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>

事实上,之前的代码片段就像你的一样。 我只是意识到你有一个属性&#34;值&#34;所有选项都相同。

所以,当你点击时,角度只是设置&#34; true&#34;在与&#34; ng-model&#34;绑定的变量中。所以,你把&#34; true&#34;每次点击,但仅此而已。

如果您想知道哪一个是检查,请为您的&#34; ng-model&#34;采取修复变量。属性,而不是随着你的选择而改变。

(我会尝试编辑你的jsfiddle)