2013-04-29 74 views
8

所以我試圖將單選按鈕綁定到對象。我花了一個小時試圖弄清楚這件事,最終承認失敗。下面是我的了:將json對象綁定到angularjs中的單選按鈕

<table> 
     <tr ng-repeat="theCustomer in customers"> 
      <td> 
       <input type="radio" ng-model="currentCustomer" value="theCustomer" id="{{theCustomer.id}}" ng-change="currentCustomer = theCustomer"> 
       <label for="{{theCustomer.id}}">{{theCustomer.name}}</label> 
      </td> 
     </tr> 
</table> 

角的東西:

bankApp.controller("BankController", function ($scope, CustomerRepository) 
{ 
    $scope.customers = []; 
    $scope.currentCustomer = {}; 

    $scope.createCustomer = function() { 
     CustomerRepository.save($scope.customer, function (customer) { 
      $scope.customers.push(customer); 
      $scope.customer = {}; 
     }); 
    }; 
}); 

目前,當我嘗試點擊單選按鈕沒有反應,甚至沒有得到大關檢查。我確信有一個非常簡單的解決方案。最終目標是讓無線電選擇中反映的客戶持有currentCustomer

回答

14
<input type="radio" ng-model="$parent.currentCustomer" name="foo" ng-value="theCustomer" id="{{theCustomer.id}}">{{theCustomer.name}}</td> 

這裏的關鍵是ng-value="theCustomer。這是角度如何知道哪個對象被選中。 html value只知道字符串值,不能映射到對象。

如果插入上面的代碼,即使以編程方式更改,收音機也會反映模型。此外,您不能忘記ng模型中的$parent,因爲ng-repeat會創建一個新的作用域。

4

顯然,讓一個無線電組在ng-repeat內工作可能有點棘手。問題在於ng-repeat創建自己的子範圍。一種解決方案是將模型綁定到$ parent。 This thread舉例說明。

我還創建了一個更類似於您的示例的working fiddle

從本質上說,我覺得你的HTML是需要返工的唯一點:

<table> 
     <tr ng-repeat="theCustomer in customers"> 
      <td><input type="radio" ng-model="$parent.currentCustomer" name="foo" value="{{theCustomer}}" id="{{theCustomer.id}}">{{theCustomer.name}}</td> 
     </tr> 
    </table> 
+2

所以這個主要工作,唯一的問題是'currentCustomer'被設置爲字符串化json而不是對象。有這個簡單的解決辦法嗎?我試圖做到這一點,沒有雙大括號,並沒有工作。 – 2013-04-30 14:32:03

+0

你希望最終結果看起來像什麼? – rGil 2013-05-01 14:59:20

+1

其實我想通了。 value屬性只接受一個字符串,不能處理一個對象。我重構了這個。謝謝! – 2013-05-01 15:30:57

3

這是因爲範圍繼承,你可以閱讀更多關於這個問題here

我在這種情況下使用的解決方案之一是將對象綁定到對象屬性,而不是像ng-model="form.currentCustomer"這樣的原始值。

演示:Plunker