2014-05-22 121 views
1

我有一些數據從一個看起來像資源回來:角 - 綁定複選框NG-模型從NG-重複

$scope.phones = [ 
    { 
     Value: <some value>, 
     IsDefault: true 
    }, 
    { 
     Value: <some value> 
     IsDefault: false 
    } 
]; 

並且爲簡化起見,這裏的轉發器:

<div ng-repeat="phone in phones"> 
    <input type="radio" name="phone" ng-model="phone.IsDefault" /> 
</div> 

我希望無論哪個無線電被檢查以相應地更新模型 - 這不會發生。在頁面加載時,不檢查任何內容。我可以使用ng-checked - 但沒有ng-model它不會綁定回數組。我是否錯過了一些簡單的東西,或者我是否寫了一個ng-change事件來手動更新數組?

截至目前,我寫了一個ng-change事件爲好,它目前看起來像:

ng-model="phone.IsDefault" ng-value="true" ng-change="newPhoneSelected($index)" 

$scope.newPhoneSelected = function (index) { 
    for (var i = 0; i < $scope.phones.length; i++) { 
     if (i == index) $scope.phones[i].IsDefault = true; 
     else $scope.phones[i].IsDefault = false; 
    } 
} 
+0

ng-value ...它是基於ng值的單選按鈕 – Dalorzo

+0

嘗試過使用ng-true-value =「true」和「ng-false-value =」false「 - no運氣 - 綁定不會發生 – tymeJV

回答

1

你缺少ng-value ...這是他們的工作基礎上value單選按鈕標記值選擇。您需要用[value="" | ng-value=""]

<input type="radio" 
     ng-model="" 
     [value="" | 
     ng-value=""]> 

像:

<input type="radio" ng-value="true" name="boolean" ng-model="myValue" /> True 
<input type="radio" ng-value="false" name="boolean" ng-model="myValue" /> False 

這裏是一個plunker demo

或者使用字符串值:

$scope.myValue = 'Car' 

HTML

<input type="radio" ng-value="'Car'" name="string1" ng-model="myValue" /> Car 
<input type="radio" ng-value="'Airplane'" name="string1" ng-model="myValue" /> Airplane 

這裏是second demo

這可能是最接近樣品是否有什麼:

http://jsfiddle.net/JbMuD/

+0

ng-false-value =「false」ng-true-value =「true」ng-model =「phone.IsDefault」 - 無變化。 – tymeJV

+0

我的收音機在一箇中繼器壽 - 所以設置一個值爲'假'不是一個選項 – tymeJV

+1

@tymeJV你缺少的重點ng-model =「myValue」比方說'汽車'只會標記選定的單選按鈕值=「汽車」 – Dalorzo

0

單選按鈕是用來選擇一個出許多價值。您想要更改一個項目(isDefault = true)和另一個項目(isDefault = false)的屬性。

的語義正確的方法是有某種defaultPhone值:

<div ng-repeat="phone in phones"> 
    <input type="radio" name="phone" ng-model="temp.defaultPhone" ng-value="phone"/> 
</div> 

因爲你的模式要求每部手機「知道」自己閹它的默認或沒有,你可以添加一個偵聽器:

$scope.$watch('temp.defaultPhone', function(defaultPhone) { 
    $scope.phones.forEach(function(phone) { 
    phone.isDefault = phone === defaultPhone; 
    }); 
}); 

這是working example