2013-04-29 6 views
8

ラジオボタンをオブジェクトにバインドしようとしています。私はこれを理解しようとしている時のように過ごし、最後に敗北を認める。ここで私が得たものです:anglejsのラジオボタンにJSONオブジェクトをバインドします

<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-repeatが新しいスコープを作成するので、ng-modelの$parentを忘れることはできません。

4

明らかに、ng-repeatの中でラジオグループを働かせるのはちょっと難しいかもしれません。問題は、ng-repeatが独自の子スコープを作成することです。 1つの解決策は、モデルを$親にバインドすることです。 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として設定されていることです。これは簡単に修正できますか?私は二重の括弧なしでそれをやってみました。 –

+0

あなたは最終結果を正確にどのように見せたいですか? – rGil

+1

私は実際にそれを理解しました。 value属性は文字列を取り、オブジェクトを扱うことはできません。私はこれに対応するためにリファクタリングしました。ありがとう! –

3

それが原因スコープの継承と、あなたは問題hereについての詳細を読むことができます。

私がこのような場合に使用する解決策の1つは、ng-model="form.currentCustomer"のようなプリミティブ値の代わりにオブジェクトプロパティにオブジェクトをバインドすることです。

デモ:Plunker

関連する問題