2015-08-09 35 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