Mark Simpson Mark Simpson - 4 months ago 14
AngularJS Question

AngularJS - Model not updating on selection of radio button generated by ng-repeat

I am generating a bunch of radio buttons using ng-repeat, and then trying to update a model when one of them is selected. This doesn't appear to be working.

The same code markup works just fine when the radio inputs are hardcoded as opposed to being generated by ng-repeat.

This works:

<input type="radio" ng-model="lunch" value="chicken" name="lunch">
<input type="radio" ng-model="lunch" value="beef" name="lunch">
<input type="radio" ng-model="lunch" value="fish" name="lunch">
{{lunch}}


This doesn't:

<input type="radio" ng-model="lunch" ng-repeat="m in meat" value="m" name="lunch">
{{lunch}}


See jsfiddle showing both here: http://jsfiddle.net/mark_up/A2qCS/1/

Any help would be appreciated.

Thanks

mpm mpm
Answer
<div ng-controller="DynamicCtrl">
    <input type="radio" ng-model="$parent.lunch" ng-repeat="m in meat"  
    ng-value="m" name="lunch">    
    {{lunch}}
</div>

Should do the trick.

As I understand it, ng-repeat creates its own $scope. so you need to refer to the $parent $scope; Yes, AngularJS is tricky. Also you need to change the value to ng-value too.

Comments