Bind JSON object to radio button in angularjs

前端 未结 3 2074
迷失自我
迷失自我 2021-02-05 14:21

So I am trying to bind radio buttons to objects. I have spent like an hour trying to figure this up and at last admit defeat. Here\'s what I got:

相关标签:
3条回答
  • 2021-02-05 14:26
    <input type="radio" ng-model="$parent.currentCustomer" name="foo" ng-value="theCustomer" id="{{theCustomer.id}}">{{theCustomer.name}}</td>
    

    The key here is the ng-value="theCustomer. This is how angular knows which object is selected. The html value only knows string values and cannot map to objects.

    If you insert the above code, the radio will reflect the model, even if it is changed programatically. Also, you can't forget the $parent in the ng-model because the ng-repeat creates a new scope.

    0 讨论(0)
  • 2021-02-05 14:45

    Apparently, getting a radio group to work inside an ng-repeat can be a bit tricky. The issue is with the ng-repeat creating its own child scope. One solution is to bind the model to the $parent. This thread gives an example.

    I also created a working fiddle that more closely resembles your example.

    In essence, I think your html is the only point that needs reworking:

    <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>
    
    0 讨论(0)
  • 2021-02-05 14:46

    It is because of the scope inheritance, you can read more about the problem here.

    One solution that I use in such a case, is to bind the object to an object property instead of a primitive value like ng-model="form.currentCustomer".

    Demo: Plunker

    0 讨论(0)
提交回复
热议问题