2015-08-09 93 views
1

这是我写的AngularJS。我想用ng-repeat的单选按钮,但它不工作

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

以下代码是工作。当我更改单选按钮时,“性别”更改值。

<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]}}" /> 

我想用单选按钮使用ng-repeat。下面的代码是行不通的。当我单击更改单选按钮时,“性别”不是响应。其实,“性别”从未表现出价值。

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

以下代码不工作。

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

这些代码有什么问题。感谢提前。

回答

0

ng-repeat为每次迭代创建一个新的作用域。由于JavaScript Prototype Inheritance affects Angular的方式以及您绑定到基元而不是对象的事实,您实际上有两个单独的属性,并且单选按钮不相互连接。

解决此问题的首选方法是绑定到对象上的属性(“在绑定中总是使用点”规则),这会自动为两个按钮指定相同的对象。即

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}}" /> 
0

看看这个PICE代码这是所有你所需要的

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

您需要提交性别来访问它的价值

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

+0

您plunker链接没有按没有你的代码。编辑了 – Claies

+0

的链接,你现在可以看到正在工作的plunker – Arashk

相关问题