Broken ng model on radio buttons with ngRepeat

Plunk: http://plnkr.co/edit/Y4ntAj2fIIpexKjkCvlD?p=preview

I am trying to create a form component that allows the user to create multiple instances of a specific data field, but to populate them from one set of inputs.

I create a radio button for each of the elements in the set, using ng-repeat, after which each switch will have a value $indexfrom repeat. The radio buttons are modeled on $scope.selectedItem, which is used to indicate the inputs to the right element.

For some reason, however, it selectedItemnever changes, even if the selected state of the switches.

I tried a similar thing with static switches, and it worked fine, which makes me think that there is a problem with the ng-modelinside ng-repeat.

+4
source share
1 answer

You need to add ngModelfor each button. Then, since each iteration ngRepeatcreates a new selection area, you have two ways to refer to your variable in the parent controller:

  • change selectedItemto object. this works because objects are passed by reference in JS, while passing a primitive, like you, does not work with two-way binding.

  • add $parent.selectedItem, selectedItem .

ngModel .

:

<input type='radio' 
       name='select' 
       id='{{$index}}' 
       ng-value='$index' 
       ng-model='$parent.selectedItem'/>

Plunker $parent

:

JS:

$scope.selectedItem = {id: -1};

HTML:

<input type='radio' 
       name='select' 
       id='{{$index}}' 
       ng-value='$index' 
       ng-model='selectedItem.id'/>

( - selectedItem selectedItem.id)

Plunker selectedItem

+4

Source: https://habr.com/ru/post/1547346/


All Articles