Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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

like image 659
Mark Simpson Avatar asked Jul 16 '13 11:07

Mark Simpson


3 Answers

<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.

like image 67
mpm Avatar answered Nov 20 '22 03:11

mpm


the above issue was discussed here

That happens because ng-repeat creates a new scope. Basically, each <input> is creating a selectedOption value on its own inner scope. To work around that, create a new container object for that value. For example, you could declare in your controller:

$scope.data = {selectedOption: x};

And then in your template, use ng-model="data.selectedOption"

in this way, ng-model gets updated .. :)

this is tricky

like image 4
Sajjad Ali Khan Avatar answered Nov 20 '22 03:11

Sajjad Ali Khan


Just need to replace value with ng-value

like image 2
Daniele Avatar answered Nov 20 '22 05:11

Daniele