0

I'm building a dynamic list of radio inputs based on JSON data coming from an API.

I'm using ngRepeat + track by, input[radio] and ngValue.

Any new XHR request will refresh the data in the scope but the currently checked radio (if any) will be unchecked.


See this plnkr demo: http://embed.plnkr.co/2q1A7krBzxIjkfwhXYcK/preview


This can be solved by using the interpolation directive in ngValue, but it feels like I'm doing it wrong:

<input type="radio" name="c" ng-value="{{ choice }}" ng-model="selected.choice" required>

This can also be solved by using ng-init but it still feels like I'm doing it wrong:

<input type="radio" name="c" ng-init="c = choice" ng-value="c" ng-model="selected.choice" required>

Can somebody please explain me what's going on?


Related questions:

Community
  • 1
  • 1
kemar
  • 520
  • 1
  • 3
  • 8

1 Answers1

1

Angular is using equality by reference here to figure out which radiobutton gets ticked, so when you replace the entire xhrData object, the reference is lost.

You can see how this works if you add

$scope.selected.choice = $scope.xhrData.all.choices[2]

to the bottom of your fetcher-function.

I'm afraid you'll have to save the choice before replacing the xhrData object and then reset it after fetching new data. I'm not aware of any other way to do it.

ivarni
  • 17,658
  • 17
  • 76
  • 92
  • Thank you very much for your answer :) I wish AngularJS used some kind of isEqual http://underscorejs.org/#isEqual for comparison. – kemar Jun 28 '14 at 09:50
  • Yes, that would have been useful in a lot of cases. I suppose they have a good reason for using object references, though I don't know what it is. I think you can get around this by using a primitive type for your `ng-model` but that opens up a door to new problems because you then have to write code to find the correct object that matches the model. Which you have to do anyway if you want to save the selection. – ivarni Jun 28 '14 at 10:01